Categories
JavaScript Answers

How to use JavaScript async/await with streams?

Spread the love

To use JavaScript async/await with streams, we use the util.promisify method.

For instance, we write

const fs = require("fs");
const crypto = require("crypto");
const util = require("util");
const stream = require("stream");

const pipeline = util.promisify(stream.pipeline);

const hash = crypto.createHash("sha1");
hash.setEncoding("hex");

const run = async () => {
  await pipeline(fs.createReadStream("/some/file/name.txt"), hash);
  console.log("Pipeline succeeded");
};

run();

to call util.promisify with stream.pipeline to return the promisified pipeline function.

And then we call pipeline with a read stream created from createReadStream to run the pipeline.

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 *