Last active
August 20, 2018 18:07
-
-
Save chaiwa-berian/d323f8828ab7f488c17eef3a08def0a5 to your computer and use it in GitHub Desktop.
Push chunk to nodejs stream on demand
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
//we could avoid buffering data altogether and only generate the data when the consumer asks for it. | |
//We can push chunks on-demand by defining a ._read function | |
//To show that our _read function is only being called when the consumer requests, | |
//we can modify our readable stream code slightly to add a delay: | |
var Readable = require('stream').Readable; | |
var rs = Readable(); | |
var c = 97 - 1; | |
rs._read = function () { | |
if (c >= 'z'.charCodeAt(0)) return rs.push(null); | |
setTimeout(function () { | |
rs.push(String.fromCharCode(++c)); | |
}, 100); | |
}; | |
rs.pipe(process.stdout); | |
process.on('exit', function () { | |
console.error('\n_read() called ' + (c - 97) + ' times'); | |
}); | |
process.stdout.on('error', process.exit); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment