Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Pattern to create a Readable Stream
// Example based in Substack Stream Handbook:
// https://github.com/substack/stream-handbook#creating-a-readable-stream
'use strict'
var inherits = require('inherits')
var duplexify = require('duplexify')
var Stream = require('readable-stream').Stream
var CONST = {
START: 64,
END: 75
}
// Option 1: based on composition
module.exports = function () {
var stream = Stream.Readable()
var counter = Number(CONST.START)
stream._read = function () {
var _this = this
var iv = setInterval(function () {
if (++counter < CONST.END) return _this.push(String.fromCharCode(counter))
clearInterval(iv)
_this.push(null)
}, 50)
}
return stream
}
// Option 2: based on inheritance
function KeyOutputStream () {
if (!(this instanceof KeyOutputStream)) return new KeyOutputStream()
Stream.Readable.call(this)
this.counter = Number(CONST.START)
}
module.exports = KeyOutputStream
inherits(KeyOutputStream, Stream.Readable)
KeyOutputStream.prototype._read = function () {
var _this = this
var iv = setInterval(function () {
if (++_this.counter < CONST.END)
return _this.push(String.fromCharCode(_this.counter))
clearInterval(iv)
_this.push(null)
}, 50)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.