Skip to content

Instantly share code, notes, and snippets.

@ianaya89
Last active November 14, 2021 11:01
Show Gist options
  • Save ianaya89/b325bbce419f599dbe4e to your computer and use it in GitHub Desktop.
Save ianaya89/b325bbce419f599dbe4e to your computer and use it in GitHub Desktop.
Custom readable stream with node js
/* Implementation */
var stream = require('stream');
// Create the custom stream
function Num(options) {
// Inherit properties
stream.Readable.call(this, options);
this._start = 0;
this._end = 100;
this._curr = this._start;
}
//Inherit prototype
Num.prototype = Object.create(stream.Readable.prototype);
Num.prototype.constructor = stream.Readable;
//Add my own implementation of read method
Num.prototype._read = function() {
var num = this._curr;
var buf = new Buffer(num.toString(), 'utf-8');
this.push(buf);
this._curr++;
if (num === this._end) {
this.push(null);
}
};
//Usage
var num = new Num();
//Listening to data event (will be executed any time that get a piece of data)
num.on('data', function(chunk) {
console.log(chunk.toString('utf-8'));
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment