Backpressure Batch Writer Stream
Write items in batches with backpressure detection pausing when downstream is slow for flow control.
Code
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();}}Report a problem with this exampleOpens a pre-filled issue on GitHub.