Weitere ähnliche Inhalte Ähnlich wie A little more advanced node (20) Mehr von Philipp Fehre (19) Kürzlich hochgeladen (20) A little more advanced node4. 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)
})
6. 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()
8. 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()
9. Why streams are great
function httpHandler(req, res) {
req.pipe(bodyParser)
.pipe(shortner)
.pipe(stringify)
.pipe(res)
}
10. 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)