| 101 | return 'req' in t; |
| 102 | } |
| 103 | export function streamToBuffer(input: NodeJS.ReadableStream | superagent.Request, maxSize = 0): Promise<Buffer> { |
| 104 | let stream: NodeJS.ReadableStream; |
| 105 | if (isSuperagentRequest(input)) { |
| 106 | const s = new PassThrough(); |
| 107 | input.pipe(s); |
| 108 | stream = s; |
| 109 | } else stream = input; |
| 110 | return new Promise((resolve, reject) => { |
| 111 | const buffers = []; |
| 112 | let length = 0; |
| 113 | function onData(data) { |
| 114 | buffers.push(data); |
| 115 | length += data.length; |
| 116 | if (maxSize && length > maxSize) { |
| 117 | stream.removeListener('data', onData); |
| 118 | reject(new Error('buffer length exceeded')); |
| 119 | } |
| 120 | } |
| 121 | stream.on('error', reject); |
| 122 | stream.on('data', onData); |
| 123 | stream.on('end', () => resolve(Buffer.concat(buffers))); |
| 124 | }); |
| 125 | } |
| 126 | |
| 127 | export function bufferToStream(buffer: Buffer): NodeJS.ReadableStream { |
| 128 | const stream = new Duplex(); |