Skip to content

Instantly share code, notes, and snippets.

@hassansin
Last active November 10, 2020 15:26
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/77e65f2e201013dba0cb to your computer and use it in GitHub Desktop.
Save hassansin/77e65f2e201013dba0cb to your computer and use it in GitHub Desktop.
Node.js Asynchronous Readable Stream
/*
Creating Asynchronous Readable Stream in NodeJS
--------------------------------------------------------
When data is pushed asynchronously to internal buffer, you'll get an asynchronous
behaviour of the stream.
See Synchronous Version: https://gist.github.com/hassansin/7f3250d79a386007ce45
*/
var Readable = require("stream").Readable;
function ReadStreamAsync(opts){
Readable.call(this, opts);
this._max = 10;
this._index = 1;
}
require("util").inherits(ReadStreamAsync, Readable)
ReadStreamAsync.prototype._read = function(n) {
if (this._index > this._max)
this.push(null);
else {
var self = this;
//asynchronously pushing data in internal buffer
setTimeout(function(){
var str = '' + self._index++;;
var buf = new Buffer(str, 'ascii');
self.push(buf)
}, 100);
}
};
console.log(new Date().toTimeString() ,"Start")
var readable = new ReadStreamAsync();
//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:55:01 GMT+0000 (UTC) Start
14:55:01 GMT+0000 (UTC) setImmediate
14:55:17 GMT+0000 (UTC) Done
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment