Skip to content

Instantly share code, notes, and snippets.

@monjer
Created July 7, 2022 07:38
Show Gist options
  • Save monjer/acec1919d7408ea2c563ded425dd4a91 to your computer and use it in GitHub Desktop.
Save monjer/acec1919d7408ea2c563ded425dd4a91 to your computer and use it in GitHub Desktop.
Convert readable stream to buffer
const streamToBuffer = (readableStream) => {
if (!readableStream) {
throw new Error('Error: readableStream can not be null')
}
return new Promise((resovle, reject) => {
const buffers = [];
readableStream.on('data', (chunks) => {
buffers.push(chunks);
});
readableStream.once('end', () => {
resovle(Buffer.concat(buffers));
});
readableStream.once('error', (error) => {
reject(error)
});
})
}
export default streamToBuffer;
@monjer
Copy link
Author

monjer commented Jul 7, 2022

import fs from 'fs';

(async () => {
  const rad = fs.createReadStream('./image.png')
  const buffers = await streamToBuffer(rad);
  const write = fs.createWriteStream('./test.png');
  write.write(buffers);
  write.end();
})()
  1. Convert stream into buffer?
  2. Node.js: How to read a stream into a buffer?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment