a little more advanced node

15
More about node.js

Upload: philipp-fehre

Post on 12-May-2015

634 views

Category:

Technology


0 download

DESCRIPTION

http://github.com/sideshowcoder/javascript-workshop

TRANSCRIPT

Page 1: A little more advanced node

More about node.js

Page 2: A little more advanced node

Building maintainable node.js software

Page 3: A little more advanced node

Streams all the way down!

Page 4: A little more advanced node

Readable Stream

var Readable = require("stream").Readable var util = require("util") !function ICanRead(options) { Readable.call(this, options) this.data = ["I", "can", "read"] } util.inherits(ICanRead, Readable) !ICanRead.prototype._read = function(size) { var chunk = this.data.shift() this.push(chunk) } !var rs = new ICanRead({}) !rs.once("readable", function() { rs.pipe(process.stdout) }) !

Page 5: A little more advanced node

Writable Stream

Page 6: A little more advanced node

var Writable = require("stream").Writable var util = require("util") !function IConcatThings(options) { Writable.call(this, options) this.data = [] } util.inherits(IConcatThings, Writable) !IConcatThings.prototype._write = function(chunk, enc, done) { this.data.push(chunk) done() } !var cs = new IConcatThings({ objectMode: true }) cs.on("finish", function() { console.log(cs.data) }) cs.write(1) cs.write(2) cs.write(3) cs.end()

Page 7: A little more advanced node

Transform Stream

Page 8: A little more advanced node

var Transform = require("stream").Transform var util = require("util") !function ITransformThings(options) { Transform.call(this, options) this._writableState.objectMode = true this._readableState.objectMode = false } util.inherits(ITransformThings, Transform) !ITransformThings.prototype._transform = function(chunk, enc, done) { this.push(chunk.toString()) done() } !var ts = new ITransformThings() ts.pipe(process.stdout) ts.write(function(foo) { return foo }) ts.write("bar") ts.write([1,2,3]) ts.end()

Page 9: A little more advanced node

Why streams are great

function httpHandler(req, res) { req.pipe(bodyParser) .pipe(shortner) .pipe(stringify) .pipe(res) }

Page 10: A little more advanced node

Explicit error handling with streams

function httpHandler(req, res) { shortner.on("error", function(err) { res.statusCode = 500 res.end("Internal Server Error") }) ! req.pipe(bodyParser) .pipe(shortner) .pipe(stringify) .pipe(res) }

Page 11: A little more advanced node

Ok just a quick thing build cat!

Page 12: A little more advanced node

Debugging… because not all code is great :(

Page 13: A little more advanced node

Seen that before?

def my_method a require "pry" binding.pry end !my_method "foo"

Page 14: A little more advanced node

And this?

function myMethod(a) { debugger } !myMethod("foo")

Page 15: A little more advanced node

using the node.js debugger