Skip to content

Instantly share code, notes, and snippets.

@jessecravens
Created November 26, 2012 22:18
Show Gist options
  • Save jessecravens/4151038 to your computer and use it in GitHub Desktop.
Save jessecravens/4151038 to your computer and use it in GitHub Desktop.
NodeJS Hacks - Streams - data pipe() flow
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