Created
November 9, 2019 20:25
-
-
Save UniBreakfast/d3af11e46893fb00d603f3a42a71945c to your computer and use it in GitHub Desktop.
wait for body / streamToString
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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