Backpressure Batch Writer Stream

Write items in batches with backpressure detection pausing when downstream is slow for flow control.

TypescriptData Fetching

Code

typescriptsnippet
1 line
import{Writable}from'node:stream';export class BatchWriter extends Writable{private buffer:any[]=[];constructor(private flush:(batch:any[])=>Promise<void>,private batchSize=100,{highWaterMark=1000}={}){super({objectMode:true,highWaterMark});}async _write(chunk:any,_:BufferEncoding,callback:(e?:Error|null)=>void){this.buffer.push(chunk);if(this.buffer.length>=this.batchSize){try{await this.flush(this.buffer);this.buffer=[];callback();}catch(e){callback(e);}}else callback();}async _final(callback:(e?:Error|null)=>void){if(this.buffer.length>0){try{await this.flush(this.buffer);callback();}catch(e){callback(e);}}else callback();}}

How the snippet works

The moving parts are the class BatchWriter.

Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed. node:stream supplies Writable — built-in surface, no package involved.

Watch out for

  • node:stream is a Node.js built-in module — it ships with the runtime, so there is nothing to install.

Applying it

Import BatchWriter from the file and call it — the rest of the code is implementation detail.

FAQ

Does this require external packages?
No — `node:stream` is a Node.js built-in module; nothing to install.