Homelab, Linux, JS & ABAP (~˘▾˘)~
 

[nodejs] Create buffer from stream

Using a promise

const streamToBuffer= async () => {
        return new Promise(function (resolve, reject) {
                const chunks = []
                stream.on('data', chunk => chunks.push(chunk))
                stream.on('end', () => resolve(Buffer.concat(chunks)))
                stream.on("error", err => reject(err))
        })
}
const buffer = await streamToBuffer()

A stream is also iterable (see here), so you can also use for await...of (example)

        const chunks = []
        for await (const chunk of stream) {
            chunks.push(chunk)
        }
        const buffer = Buffer.concat(chunks)

Leave a Reply

Your email address will not be published. Required fields are marked *