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)