Created
January 7, 2017 05:49
-
-
Save myndzi/cb92b1e35f1aec5c6baafef63ae49eb4 to your computer and use it in GitHub Desktop.
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
| 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