1 | 'use strict';
|
2 | const {PassThrough: PassThroughStream} = require('stream');
|
3 |
|
4 | module.exports = options => {
|
5 | options = {...options};
|
6 |
|
7 | const {array} = options;
|
8 | let {encoding} = options;
|
9 | const isBuffer = encoding === 'buffer';
|
10 | let objectMode = false;
|
11 |
|
12 | if (array) {
|
13 | objectMode = !(encoding || isBuffer);
|
14 | } else {
|
15 | encoding = encoding || 'utf8';
|
16 | }
|
17 |
|
18 | if (isBuffer) {
|
19 | encoding = null;
|
20 | }
|
21 |
|
22 | const stream = new PassThroughStream({objectMode});
|
23 |
|
24 | if (encoding) {
|
25 | stream.setEncoding(encoding);
|
26 | }
|
27 |
|
28 | let length = 0;
|
29 | const chunks = [];
|
30 |
|
31 | stream.on('data', chunk => {
|
32 | chunks.push(chunk);
|
33 |
|
34 | if (objectMode) {
|
35 | length = chunks.length;
|
36 | } else {
|
37 | length += chunk.length;
|
38 | }
|
39 | });
|
40 |
|
41 | stream.getBufferedValue = () => {
|
42 | if (array) {
|
43 | return chunks;
|
44 | }
|
45 |
|
46 | return isBuffer ? Buffer.concat(chunks, length) : chunks.join('');
|
47 | };
|
48 |
|
49 | stream.getBufferedLength = () => length;
|
50 |
|
51 | return stream;
|
52 | };
|