Skip to content

Instantly share code, notes, and snippets.

@myndzi
Created January 7, 2017 05:49
Show Gist options
  • Select an option

  • Save myndzi/cb92b1e35f1aec5c6baafef63ae49eb4 to your computer and use it in GitHub Desktop.

Select an option

Save myndzi/cb92b1e35f1aec5c6baafef63ae49eb4 to your computer and use it in GitHub Desktop.
const Transform = require('stream').Transform;
const util = require('util');
function ChunkStream(options) {
if (!(this instanceof ChunkStream))
return new ChunkStream(options);
Transform.call(this, options);
this.chunkSize = options.chunkSize || 1500;
this._chunks = [ ];
this._size = 0;
}
util.inherits(ChunkStream, Transform);
ChunkStream.prototype._transform = function (_chunk, encoding, callback) {
let chunk = Buffer.isBuffer(_chunk) ? _chunk : Buffer.from(_chunk, encoding);
this._chunks.push(chunk);
this._size += chunk.length;
if (this._size > this.chunkSize) {
this._flush(callback);
} else {
callback();
}
};
ChunkStream.prototype._flush = function (callback) {
this.push(Buffer.concat(this._chunks));
this._chunks.length = 0;
this._size = 0;
};
module.exports = ChunkStream;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment