wallet-core/node_modules/get-stream/index.js

52 lines
1.2 KiB
JavaScript
Raw Normal View History

2017-05-28 00:38:50 +02:00
'use strict';
2017-08-14 05:01:11 +02:00
const bufferStream = require('./buffer-stream');
2017-05-28 00:38:50 +02:00
function getStream(inputStream, opts) {
if (!inputStream) {
return Promise.reject(new Error('Expected a stream'));
}
2017-08-14 05:01:11 +02:00
opts = Object.assign({maxBuffer: Infinity}, opts);
const maxBuffer = opts.maxBuffer;
let stream;
let clean;
const p = new Promise((resolve, reject) => {
const error = err => {
if (err) { // null check
err.bufferedData = stream.getBufferedValue();
}
reject(err);
};
2017-05-28 00:38:50 +02:00
stream = bufferStream(opts);
inputStream.once('error', error);
inputStream.pipe(stream);
2017-08-14 05:01:11 +02:00
stream.on('data', () => {
2017-05-28 00:38:50 +02:00
if (stream.getBufferedLength() > maxBuffer) {
reject(new Error('maxBuffer exceeded'));
}
});
stream.once('error', error);
stream.on('end', resolve);
2017-08-14 05:01:11 +02:00
clean = () => {
// some streams doesn't implement the `stream.Readable` interface correctly
2017-05-28 00:38:50 +02:00
if (inputStream.unpipe) {
inputStream.unpipe(stream);
}
};
});
p.then(clean, clean);
2017-08-14 05:01:11 +02:00
return p.then(() => stream.getBufferedValue());
2017-05-28 00:38:50 +02:00
}
module.exports = getStream;
2017-08-14 05:01:11 +02:00
module.exports.buffer = (stream, opts) => getStream(stream, Object.assign({}, opts, {encoding: 'buffer'}));
module.exports.array = (stream, opts) => getStream(stream, Object.assign({}, opts, {array: true}));