Readable Stream From Async Generator

Create a Node.js Readable stream from an async generator with backpressure and cancellation support.

JavascriptData Fetching

Code

javascriptsnippet
1 line
import{Readable}from'node:stream';export function fromAsync(generator){return Readable.from(generator());}export function fromIterable(iterable,{objectMode=true}={}){return new Readable({objectMode,async read(){for await(const item of iterable){if(!this.push(item))return;}this.push(null);}});}export async function* range(start,end,step=1){for(let i=start;i<end;i+=step)yield i;}export async function* takeWhile(iterable,predicate){for await(const item of iterable){if(!predicate(item))return;yield item;}}

Inside the snippet

The working surface is the functions fromAsync and fromIterable — everything else is wiring.

Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed. The import names the platform contact area: Readable, all from node:stream.

A fresh value is allocated for the result; the arguments stay untouched.

Watch out for

  • The only import, node:stream, is part of the Node.js standard library.

Where this earns its keep

Signature: export function fromAsync(generator)

Treat fromAsync as the API: import it, and ignore the supporting code.

FAQ

Does `fromAsync` modify its input?
No. Nothing passed in is written to, which makes the call safe on shared data.
Is the imported module an npm package?
No — `node:stream` is built into Node.js. The `node:` prefix marks core modules, so there is nothing to add to a project.