Created
November 26, 2012 22:18
-
-
Save jessecravens/4151038 to your computer and use it in GitHub Desktop.
NodeJS Hacks - Streams - data pipe() flow
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
exports.example5= function(req, res){ | |
// Set both readable and writable in constructor. | |
var NopStream = function () { | |
this.readable = true; | |
this.writable = true; | |
}; | |
// Inherit from base stream class. | |
require('util').inherits(NopStream, require('stream')); | |
// Extract args to `write` and emit as `data` event. | |
NopStream.prototype.write = function () { | |
console.log("writing data ..."); | |
args = Array.prototype.slice.call(arguments, 0); | |
this.emit.apply(this, ['data'].concat(args)) | |
}; | |
// Extract args to `end` and emit as `end` event. | |
NopStream.prototype.end = function () { | |
console.log("end stream from pipe."); | |
args = Array.prototype.slice.call(arguments, 0); | |
this.emit.apply(this, ['end'].concat(args)) | |
}; | |
// Download the same page again, but with the NOP stream | |
// in the middle. | |
require('http').get("http://html5hacks.com/", function(response) { | |
var outStream = require('fs').createWriteStream("html5hacks.txt"); | |
response | |
// Wow, that's a lot of nop's! | |
.pipe(new NopStream()) | |
.pipe(new NopStream()) | |
.pipe(new NopStream()) | |
.pipe(new NopStream()) | |
// OK, finally write out to file. | |
.pipe(outStream); | |
}); | |
res.render('example5', { title: 'Example5' }) | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment