1 | "use strict";
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 |
|
17 |
|
18 | Object.defineProperty(exports, "__esModule", { value: true });
|
19 | const _ = require("lodash");
|
20 | const index_1 = require("../index");
|
21 | const events_1 = require("../events");
|
22 | const isStream = require("is-stream");
|
23 |
|
24 |
|
25 |
|
26 |
|
27 |
|
28 |
|
29 |
|
30 |
|
31 | async function asBuffer(data, enc) {
|
32 | enc = index_1.normalizeString(enc);
|
33 | if ('' === enc) {
|
34 | enc = 'utf8';
|
35 | }
|
36 | return await asBufferInner(data, enc, 0);
|
37 | }
|
38 | exports.asBuffer = asBuffer;
|
39 | async function asBufferInner(data, enc, level) {
|
40 | if (level > 63) {
|
41 | throw new Error('StackOverflow: asBufferInner()');
|
42 | }
|
43 | if (Buffer.isBuffer(data)) {
|
44 | return data;
|
45 | }
|
46 | if (isStream(data)) {
|
47 | return await readAll(data, enc);
|
48 | }
|
49 | if (_.isFunction(data)) {
|
50 | return await asBufferInner(await Promise.resolve(data(enc)), enc, level + 1);
|
51 | }
|
52 | return Buffer.from(index_1.toStringSafe(data), enc);
|
53 | }
|
54 |
|
55 |
|
56 |
|
57 |
|
58 |
|
59 |
|
60 |
|
61 |
|
62 | function readAll(stream, enc) {
|
63 | enc = index_1.normalizeString(enc);
|
64 | if ('' === enc) {
|
65 | enc = undefined;
|
66 | }
|
67 | return new Promise((resolve, reject) => {
|
68 | let buff;
|
69 | let dataListener;
|
70 | let endListener;
|
71 | let errorListener;
|
72 | let completedInvoked = false;
|
73 | const COMPLETED = (err) => {
|
74 | if (completedInvoked) {
|
75 | return;
|
76 | }
|
77 | completedInvoked = true;
|
78 | events_1.tryRemoveListener(stream, 'data', dataListener);
|
79 | events_1.tryRemoveListener(stream, 'end', endListener);
|
80 | events_1.tryRemoveListener(stream, 'error', errorListener);
|
81 | if (err) {
|
82 | reject(err);
|
83 | }
|
84 | else {
|
85 | resolve(buff);
|
86 | }
|
87 | };
|
88 | errorListener = (err) => {
|
89 | if (err) {
|
90 | COMPLETED(err);
|
91 | }
|
92 | };
|
93 | dataListener = (chunk) => {
|
94 | try {
|
95 | if (!chunk || chunk.length < 1) {
|
96 | return;
|
97 | }
|
98 | if (_.isString(chunk)) {
|
99 | chunk = Buffer.from(chunk, enc);
|
100 | }
|
101 | buff = Buffer.concat([buff, chunk]);
|
102 | }
|
103 | catch (e) {
|
104 | COMPLETED(e);
|
105 | }
|
106 | };
|
107 | endListener = () => {
|
108 | COMPLETED(null);
|
109 | };
|
110 | try {
|
111 | stream.on('error', errorListener);
|
112 | buff = Buffer.alloc(0);
|
113 | stream.once('end', endListener);
|
114 | stream.on('data', dataListener);
|
115 | }
|
116 | catch (e) {
|
117 | COMPLETED(e);
|
118 | }
|
119 | });
|
120 | }
|
121 | exports.readAll = readAll;
|
122 |
|
\ | No newline at end of file |