Categories
JavaScript Answers

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

Spread the love

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 return a promise that resolves the the combined chunks from the stream.

For instance, we write

const streamToString = (stream) => {
  const chunks = [];
  return new Promise((resolve, reject) => {
    stream.on("data", (chunk) => chunks.push(Buffer.from(chunk)));
    stream.on("error", (err) => reject(err));
    stream.on("end", () => resolve(Buffer.concat(chunks).toString("utf8")));
  });
};

to create a promise with the Promise constructor.

We call it with a callback that calls streams.on with 'data' to get the chunk from the stream and then push that to chunks with push.

Then we call on with 'end' with a callback that combines the chunks with

Buffer.concat(chunks).toString("utf8")

And then we call resolve with the buffer converted to a string with toString to use that as the promise resolve value.

Then we write

const result = await streamToString(stream);

in an async function to get the value from the stream.

Conclusion

To read the contents of a Node.js stream into a string variable, we can return a promise that resolves the the combined chunks from the stream.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *