Last active
November 10, 2020 15:26
-
-
Save hassansin/77e65f2e201013dba0cb to your computer and use it in GitHub Desktop.
Node.js Asynchronous Readable Stream
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
/* | |
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