import { pipeline , Readable , Writable , WritableOptions } from "stream" ; import { promisify } from "util" ; export const pipelineAsync = promisify ( pipeline ) ; export class MemoryStream extends Writable { buffers : Buffer [ ] = [ ] ; constructor ( opts ? ) { super ( opts ) ; } _write ( chunk , encoding , callback ) { if ( chunk instanceof Buffer ) { this . buffers . push ( chunk ) ; } else { this . buffers . push ( Buffer . from ( chunk , encoding ) ) ; } callback ( null ) ; } getData ( ) { if ( this . buffers . length === 1 ) { return this . buffers [ 0 ] ; } return Buffer . concat ( this . buffers ) ; } } export async function readStream ( stream , ignoreErrors = false ) { const memStream = new MemoryStream ( ) ; if ( ignoreErrors ) { try { await pipelineAsync ( stream , memStream ) ; } catch ( error ) { console . debug ( `readStream error: ${ error }` ) ; } } else { await pipelineAsync ( stream , memStream ) ; } return memStream . getData ( ) ; }