Skip to content

Instantly share code, notes, and snippets.

@mdobson
Created February 26, 2014 13:57
Show Gist options
  • Save mdobson/9229852 to your computer and use it in GitHub Desktop.
Save mdobson/9229852 to your computer and use it in GitHub Desktop.
Wrapping streams with other streams
var Readable = require('stream').Readable;
var util = require('util');
var Incoming = module.exports = function (opt) {
this.stream = opt.stream;
Readable.call(this, opt);
};
util.inherits(Incoming, Readable);
Incoming.prototype._read = function(n) {
var chunk = this.stream.read();
if(chunk) {
this.push(chunk);
}
};
function Counter(opt) {
Readable.call(this, opt);
this._max = 10000;
this._index = 1;
}
util.inherits(Counter, Readable);
Counter.prototype._read = function() {
var i = this._index++;
if( i > this._max)
{
this.push(null);
} else {
var str = '' + i;
var buf = new Buffer(str, 'ascii');
this.push(buf);
}
};
var c = new Counter();
var i = new Incoming({stream: c});
i.on('data', function(data) {
console.log(data.toString());
});
i.on('end', function() {
console.log('done');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment