How to read a stream into a buffer with Node.js?

Sometimes, we want to read a stream into a buffer with Node.js.

In this article, we’ll look at how to read a stream into a buffer with Node.js.

How to read a stream into a buffer with Node.js?

To read a stream into a buffer with Node.js, we can use the on method to listen for the data event.

For instance, we write

const bufs = [];
stdout.on('data', (d) => {
  bufs.push(d);
});
stdout.on('end', () => {
  const buf = Buffer.concat(bufs);
})

to call stdout.on with 'data' to listen for the data event.

In the callback, we call bufs.push with d to append d into the bufs array.

And then we call on with 'end' to listen to the end event which is triggered when the stream is finished.

In the callback, we call Buffer.concat with bufs to combine the buffer chunks into a single buffer object.

Conclusion

To read a stream into a buffer with Node.js, we can use the on method to listen for the data event.