How to read the contents of a Node.js stream into a string variable?

Sometimes, we want to read the contents of a Node.js stream into a string variable.

In this article, we’ll look at how to read the contents of a Node.js stream into a string variable.

How to read the contents of a Node.js stream into a string variable?

To read the contents of a Node.js stream into a string variable, we can use the Buffer.concat method.

For instance, we write

const chunks = [];

readStream.on("data", (chunk) => {
  chunks.push(chunk);
});

readStream.on("end", () => {
  res.send(Buffer.concat(chunks));
});

to push the chunk into chunks when data received in the data event callback.

Then we call Buffer.concat with chunks to combine the chunks in the end event callback when we’re done reading the stream to return a file.

Conclusion

To read the contents of a Node.js stream into a string variable, we can use the Buffer.concat method.