In Nodejs when dealing with non-text files (e.g. images) IO operations such as transferring via network or reading from disk, there is a big chance to receive the content as stream.Readable, and before we can process the complete data in memory such as calculating the bytes size or image dimensions, we need save the stream to buffer and here are a few ways.

with for await to iterate over the async iterable stream

const chunks = [];
for await (const chunk of stream) {
  chunks.push(chunk);
}
const buffer = Buffer.concat(chunks);

with event listener to listen to data and event events from the stream

const chunks = [];
stream.on('data', (chunk) => {
  chunks.push(chunk);
});
stream.on('end', () => {
  const buffer = Buffer.concat(chunks);
});

There is a very good article with more details and information: Understanding Streams in Node.js

Post tagged with: nodejs, js