Stream Pipeline With Backpressure
Compose Node.js streams with pipe and backpressure handling for memory-efficient data transformation.
Code
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();}});}How it works
The working surface is the functions createTransform, pipeThrough and batchTransform — everything else is wiring.
Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed. pipeline, Transform come from node:stream — Node.js core modules the runtime ships with.
The result is a fresh construction, so callers can keep their originals.
What to watch for
node:streamis a Node.js built-in module — it ships with the runtime, so there is nothing to install.
Using it
The primary signature is export function createTransform(fn)
createTransform is what another module would consume; nothing else here is load-bearing for callers.
FAQ
- Does `createTransform` modify its input?
- No. The code builds and returns a new value and leaves the arguments untouched, so it is safe to call on shared or frozen data structures.
- Does this require external packages?
- No — `node:stream` is a Node.js built-in module; nothing to install.
Report a problem with this exampleOpens a pre-filled issue on GitHub.