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.