1'use strict'; 2const bufferStream = require('./buffer-stream'); 3 4function getStream(inputStream, opts) { 5 if (!inputStream) { 6 return Promise.reject(new Error('Expected a stream')); 7 } 8 9 opts = Object.assign({maxBuffer: Infinity}, opts); 10 11 const maxBuffer = opts.maxBuffer; 12 let stream; 13 let clean; 14 15 const p = new Promise((resolve, reject) => { 16 const error = err => { 17 if (err) { // null check 18 err.bufferedData = stream.getBufferedValue(); 19 } 20 21 reject(err); 22 }; 23 24 stream = bufferStream(opts); 25 inputStream.once('error', error); 26 inputStream.pipe(stream); 27 28 stream.on('data', () => { 29 if (stream.getBufferedLength() > maxBuffer) { 30 reject(new Error('maxBuffer exceeded')); 31 } 32 }); 33 stream.once('error', error); 34 stream.on('end', resolve); 35 36 clean = () => { 37 // some streams doesn't implement the `stream.Readable` interface correctly 38 if (inputStream.unpipe) { 39 inputStream.unpipe(stream); 40 } 41 }; 42 }); 43 44 p.then(clean, clean); 45 46 return p.then(() => stream.getBufferedValue()); 47} 48 49module.exports = getStream; 50module.exports.buffer = (stream, opts) => getStream(stream, Object.assign({}, opts, {encoding: 'buffer'})); 51module.exports.array = (stream, opts) => getStream(stream, Object.assign({}, opts, {array: true})); 52