Last active
March 17, 2016 12:28
-
-
Save Kikobeats/d48f42ebf81fb5b2414e to your computer and use it in GitHub Desktop.
Pattern to create a Readable Stream
This file contains 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
// 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