Skip to content

Instantly share code, notes, and snippets.

@joona
Created February 15, 2017 12:21
Show Gist options
  • Select an option

  • Save joona/e41a5750defe8e9a3be6bcb7c6f48ff9 to your computer and use it in GitHub Desktop.

Select an option

Save joona/e41a5750defe8e9a3be6bcb7c6f48ff9 to your computer and use it in GitHub Desktop.
class ChunkingObjectStream extends WriteableStream {
constructor(options) {
options.objectMode = true;
super(options);
this.chunkSize = options.chunkSize || 100;
this.queue = [];
this.counter = 0;
this.emitted = 0;
this.once('finish', () => {
this._flushOnFinish();
});
}
_write(chunk, encoding, callback) {
this.counter++;
if(this.queue.length == this.chunkSize) {
this._flushQueue();
}
this.queue.push(chunk);
callback();
}
_flushQueue() {
this.emitted += this.queue.length;
this.emit('chunk', this.queue, this.emitted);
this.queue = [];
}
_flushOnFinish() {
this._flushQueue();
this.emit('done', this.counter, this.emitted);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment