Skip to content

Instantly share code, notes, and snippets.

@4xle
Forked from johndstein/any-source-readable.js
Created June 7, 2018 18:54
Show Gist options
  • Save 4xle/825b755864113a64fa924c9f868c0d06 to your computer and use it in GitHub Desktop.
Save 4xle/825b755864113a64fa924c9f868c0d06 to your computer and use it in GitHub Desktop.
Custom Node.js readable stream that accepts data from any source
'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