nodejs stream to buffer
/**
*
* @param {ReadableStream} stream
*/
async function streamToBuffer(stream) {
return new Promise((resolve, reject) => {
const buffers = [];
stream.on('data', (chunk) => {
buffers.push(chunk);
});
stream.on('end', () => {
resolve(Buffer.concat(buffers))
})
stream.on('error', (error) => {
reject(error)
})
});
}
asyncIterator
/**
*
* @param {ReadableStream} stream
*/
async function streamToBuffer2(stream) {
const buffers = [];
for await (const data of stream) {
buffers.push(data);
}
return Buffer.concat(buffers);
}
或者 Array.fromAsync
Buffer.concat(await Array.fromAsync(stream))