nodejs stream to buffer

2023/12/02
/**
 *
 * @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

stream实现了异步迭代协议所以

/**
 *
 * @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));