|
| 1 | +const stream = require('stream'); |
| 2 | +const async = require('async'); |
| 3 | + |
| 4 | +class StreamBuffer extends stream.Writable { |
| 5 | + constructor(options) { |
| 6 | + super(options); |
| 7 | + |
| 8 | + options = options || {}; |
| 9 | + |
| 10 | + this.maxBufferSize = options.maxBufferSize || StreamBuffer.MAX_BUFFER_SIZE; |
| 11 | + |
| 12 | + this.buffered = []; |
| 13 | + this.bufferedAmount = 0; |
| 14 | + |
| 15 | + this.hadError = null; |
| 16 | + this.didFinish = false; |
| 17 | + |
| 18 | + this.once('finish', () => this.didFinish = true); |
| 19 | + this.once('error', (error) => this.hadError = error); |
| 20 | + } |
| 21 | + |
| 22 | + _write(chunk, encoding, callback) { |
| 23 | + if (this.bufferedAmount === this.maxBufferSize) |
| 24 | + return setImmediate(callback); |
| 25 | + |
| 26 | + if (this.bufferedAmount + chunk.length > this.maxBufferSize) { |
| 27 | + chunk = chunk.slice(0, this.maxBufferSize - this.bufferedAmount); |
| 28 | + } |
| 29 | + |
| 30 | + this.bufferedAmount += chunk.length; |
| 31 | + |
| 32 | + this.buffered.push(chunk); |
| 33 | + |
| 34 | + setImmediate(callback); |
| 35 | + } |
| 36 | + |
| 37 | + toString(encoding, callback) { |
| 38 | + if (typeof encoding === 'function') { |
| 39 | + callback = encoding; |
| 40 | + encoding = 'utf8'; |
| 41 | + } |
| 42 | + |
| 43 | + encoding = encoding || 'utf8'; |
| 44 | + |
| 45 | + if (!callback) { |
| 46 | + return this.toBuffer().toString(encoding); |
| 47 | + } |
| 48 | + |
| 49 | + this.toBuffer((error, buffer) => { |
| 50 | + if (error) return callback(error); |
| 51 | + |
| 52 | + callback(null, buffer.toString(encoding)); |
| 53 | + }); |
| 54 | + } |
| 55 | + |
| 56 | + toBuffer(callback) { |
| 57 | + if (!callback) { |
| 58 | + return Buffer.concat(this.buffered); |
| 59 | + } |
| 60 | + |
| 61 | + if (this.hadError || this.didFinish) { |
| 62 | + return setImmediate(callback, this.hadError, this.toBuffer()); |
| 63 | + } |
| 64 | + |
| 65 | + async.race([ |
| 66 | + (callback) => this.on('error', callback), |
| 67 | + (callback) => this.on('finish', () => callback(null, this.toBuffer())) |
| 68 | + ], callback); |
| 69 | + } |
| 70 | +} |
| 71 | + |
| 72 | +StreamBuffer.MAX_BUFFER_SIZE = 10 * 1024 * 1024; |
| 73 | + |
| 74 | +module.exports = StreamBuffer; |
0 commit comments