Categories
JavaScript Answers

How to use JavaScript async/await with streams?

Spread the love

Sometimes, we want to use JavaScript async/await with streams.

In this article, we’ll look at how to use JavaScript async/await with streams.

How to use JavaScript async/await with streams?

To use JavaScript async/await with streams, we can use the stream/promises module.

For instance, we write

const { pipeline } = require("stream/promises");

const run = async () => {
  await pipeline(
    fs.createReadStream("archive.tar"),
    zlib.createGzip(),
    fs.createWriteStream("archive.tar.gz")
  );
  console.log("Pipeline succeeded.");
};

run().catch(console.error);

to define the run function that calls pipeline with the streams inside.

We call createReadStream to create a read stream for the archive.tar file.

Then we call createGzip to create a gzip file.

And then we call createWriteStream to write the gzipped archive.tar file to archive.tar.gz.

We can use the stream/promises module since Node 15.

Conclusion

To use JavaScript async/await with streams, we can use the stream/promises module.

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 *