Skip to content

Instantly share code, notes, and snippets.

@Kikobeats
Last active March 17, 2016 12:28
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 Kikobeats/d48f42ebf81fb5b2414e to your computer and use it in GitHub Desktop.
Save Kikobeats/d48f42ebf81fb5b2414e to your computer and use it in GitHub Desktop.
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