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

52 lines
847 B
JavaScript
Raw Normal View History

2017-08-14 05:01:11 +02:00
'use strict';
const PassThrough = require('stream').PassThrough;
2017-05-28 00:38:50 +02:00
2017-08-14 05:01:11 +02:00
module.exports = opts => {
opts = Object.assign({}, opts);
2017-05-28 00:38:50 +02:00
2017-08-14 05:01:11 +02:00
const array = opts.array;
let encoding = opts.encoding;
const buffer = encoding === 'buffer';
let objectMode = false;
2017-05-28 00:38:50 +02:00
if (array) {
objectMode = !(encoding || buffer);
} else {
encoding = encoding || 'utf8';
}
if (buffer) {
encoding = null;
}
2017-08-14 05:01:11 +02:00
let len = 0;
const ret = [];
const stream = new PassThrough({objectMode});
2017-05-28 00:38:50 +02:00
if (encoding) {
stream.setEncoding(encoding);
}
2017-08-14 05:01:11 +02:00
stream.on('data', chunk => {
2017-05-28 00:38:50 +02:00
ret.push(chunk);
if (objectMode) {
len = ret.length;
} else {
len += chunk.length;
}
});
2017-08-14 05:01:11 +02:00
stream.getBufferedValue = () => {
2017-05-28 00:38:50 +02:00
if (array) {
return ret;
}
2017-08-14 05:01:11 +02:00
2017-05-28 00:38:50 +02:00
return buffer ? Buffer.concat(ret, len) : ret.join('');
};
2017-08-14 05:01:11 +02:00
stream.getBufferedLength = () => len;
2017-05-28 00:38:50 +02:00
return stream;
};