Created
February 26, 2014 13:57
-
-
Save mdobson/9229852 to your computer and use it in GitHub Desktop.
Wrapping streams with other streams
This file contains hidden or 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
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