stream-to-async-iterator provides a wrapper that implements Symbol.asyncIterator. This will allow streams to be
usable as async iterables that can be used in for-await-of loops.
Supports node.js 12 and up.
With NPM:
npm install stream-to-async-iteratorWith Yarn:
yarn add stream-to-async-iteratorThe included examples use async/await syntax for for-of loops. This assumes you are in an environment that natively
supports this new syntax, or that you use a tool such as Babel. In addition, for async iterators to work properly,
the Symbol.asyncIterator symbol must be defined. Core-js can help with that.
Import the StreamToAsyncIterator class and pass the stream to its constructor. The iterator instance can be directly used in for-of contexts.
If the stream is in object mode, each iteration will produce the next object. See the node documentation for more information.
#!/usr/bin/env node
"use strict";const{ Readable }=require("stream");constS2A=require("../").default;(asyncfunction(){constreadStream=Readable.from([1,2,3]);forawait(constchunkofnewS2A(readStream)){console.dir({ chunk });}})();Outputs:
{ chunk: 1 }
{ chunk: 2 }
{ chunk: 3 }