Last active
June 7, 2018 18:54
-
-
Save johndstein/e9d0982418b8b545d5609aa64d72b190 to your computer and use it in GitHub Desktop.
Custom Node.js readable stream that accepts data from any source
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
'use strict'; | |
const Readable = require('stream').Readable; | |
// Easily turn anything into a readable stream. | |
// This is pretty much taken verbatim from the node documentation. Why re-invent | |
// the wheel? | |
// https://nodejs.org/api/stream.html#stream_readable_push_chunk_encoding | |
// AnySourceReadable extends the standard node readable stream to accept data | |
// from any source that correctly implements readStart(), readStop(), | |
// onData(chunk), and onEnd(); | |
class AnySourceReadable extends Readable { | |
constructor(source, options) { | |
super(options); | |
this._source = source; | |
this._source.onData = (chunk) => { | |
// this.push() is a built in Node.js stream method that returns false when | |
// the downstream can't handle any more data. Once this.push() returns | |
// false _read() will not be called again till the downstream is ready to | |
// receive more data. | |
if (!this.push(chunk)) | |
this._source.readStop(); | |
}; | |
this._source.onEnd = () => { | |
console.log('onEnd'); | |
// pushing null tells the downstream we are done. there's no more data to | |
// be had. | |
this.push(null); | |
}; | |
} | |
// Any time the downstream wants data, _read() is called. We may or may not | |
// have data to send. If not, we just do nothing. If so we send data via | |
// this.push(chunk). | |
_read(size) { | |
this._source.readStart(); | |
} | |
} | |
exports = module.exports = AnySourceReadable; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment