Skip to content

Instantly share code, notes, and snippets.

@hassansin
Last active December 25, 2019 02:08
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hassansin/7f3250d79a386007ce45 to your computer and use it in GitHub Desktop.
Save hassansin/7f3250d79a386007ce45 to your computer and use it in GitHub Desktop.
Node.js Synchronous Readable Stream
/*
Creating Synchronous Readable Stream in NodeJS
--------------------------------------------------
When data is pushed synchronously to internal buffer, you'll get the synchronous
behaviour of the stream. This would block the rest of the code from being executed in
the next event loop iteration.
In the example setImmediate should be called immediatley in next event loop iteration.
But since the stream is synchronously reading data, it can't execute other callbacks.
See asynchronous version: https://gist.github.com/hassansin/77e65f2e201013dba0cb
*/
var Readable = require("stream").Readable;
function ReadStreamSync(opts){
Readable.call(this, opts);
this._max = 1000000;
this._index = 1;
}
require("util").inherits(ReadStreamSync, Readable)
ReadStreamSync.prototype._read = function(n) {
var i = this._index++;
if (i > this._max)
this.push(null);
else {
var str = '' + i;
var buf = new Buffer(str, 'ascii');
//synchronously pushing data in buffer
this.push(buf);
}
};
console.log(new Date().toTimeString() ,"Start")
var readable = new ReadStreamSync();
//reading starts from next tick
readable.on('data', function(chunk) {
//do stuff
});
readable.on('end', function(){
console.log(new Date().toTimeString() ,'Done');
});
//scheduled to run on next tick
setImmediate(function(){
console.log(new Date().toTimeString() ,'setImmediate')
})
/*
Output:
---------------
14:41:57 GMT+0000 (UTC) Start
14:41:59 GMT+0000 (UTC) Done
14:41:59 GMT+0000 (UTC) setImmediate
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment