Stream Pipeline With Backpressure

Compose Node.js streams with pipe and backpressure handling for memory-efficient data transformation.

JavascriptData Fetching

Code

snippet
import{pipeline,Transform}from'node:stream';export function createTransform(fn){return new Transform({objectMode:true,async transform(chunk,encoding,callback){try{const result=await fn(chunk);this.push(result);callback();}catch(e){callback(e);}}});}export async function pipeThrough(source,transforms,destination){const streams=[source,...transforms,destination];await pipeline(streams);}export function batchTransform(size){let buffer=[];return new Transform({objectMode:true,transform(chunk,_,cb){buffer.push(chunk);if(buffer.length>=size){this.push(buffer);buffer=[];}cb();},flush(cb){if(buffer.length>0)this.push(buffer);cb();}});}