Skip to content

Instantly share code, notes, and snippets.

@UniBreakfast
Created November 9, 2019 20:25
Show Gist options
  • Save UniBreakfast/d3af11e46893fb00d603f3a42a71945c to your computer and use it in GitHub Desktop.
Save UniBreakfast/d3af11e46893fb00d603f3a42a71945c to your computer and use it in GitHub Desktop.
wait for body / streamToString
// short version I prefer
const wait = (stream, parts=[])=> new Promise((resolve, reject)=>
stream.on('error', reject).on('data', part => parts.push(part))
.on('end', ()=> resolve(Buffer.concat(parts).toString('utf8'))))
// usage example
wait(req).then(body => console.log(body))
// original by Marlon Bernardes
function streamToString (stream) {
const chunks = []
return new Promise((resolve, reject) => {
stream.on('data', chunk => chunks.push(chunk))
stream.on('error', reject)
stream.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')))
})
}
// his usage example
const result = await streamToString(stream)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment