I am so curious about the below program.This program push the letters 'a' through 'z', inclusive , into a readable stream only when the consumer requests. I understand from the docs that _read()
implementation is called by internal Readable
class methods. If you run this program from terminal using the command node app.js | head -c5
then we can see that _read()
is only called 5 times when we only request 5 bytes and thus it prints only abcde
.
I would like to know where in the Node source code this _read()
implementation is called?. Or where in Node source code _read()
is getting called 5 times when we request for 5 bytes of data?.
I am so curious to know this, if someone can help me figure out it that would be great.
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);