convert readable stream to buffer in typescript

index.ts
import { Readable } from 'stream';

async function streamToBuffer(stream: Readable): Promise<Buffer> {
    const chunks: any[] = [];
    return new Promise((resolve, reject) => {
        stream.on('data', (chunk) => {
            chunks.push(chunk);
        });
        stream.on('end', () => {
            resolve(Buffer.concat(chunks));
        });
        stream.on('error', (err) => {
            reject(err);
        });
    });
}

// Example usage
const readableStream = createReadableStreamSomehow();
streamToBuffer(readableStream).then((buffer) => {
    console.log(buffer);
}).catch((err) => {
    console.error(err);
});
631 chars
25 lines

related categories

gistlibby LogSnag