Readable Stream From Async Generator
Create a Node.js Readable stream from an async generator with backpressure and cancellation support.
Code
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;}}Report a problem with this exampleOpens a pre-filled issue on GitHub.