Got: How to get the response body from a stream?

Created on 24 Apr 2020  路  6Comments  路  Source: sindresorhus/got

What would you like to discuss?

How do we get the response.body when using got.stream ?

got.stream.put(options).on('response', (response) => {
  console.log(response.body); // returns undefined
});

Checklist

  • [x] I have read the documentation.

Most helpful comment

You could use https://github.com/sindresorhus/get-stream to simplify that.

All 6 comments

This is a Node.js basic question. Google "how to read a readable stream in Node.js"

I finally got it:

const body = [];

got.stream.put(options)
.on('end', () => {
    console.log(Buffer.concat(body).toString());
})
.on('data', (chunk) => {
    body.push(chunk);
});

You could use https://github.com/sindresorhus/get-stream to simplify that.

Thanks @sindresorhus it was easier than I thought.

I was just confused by the response event. :P

The response gives the raw response, and in 99% you don't need it unless you want to modify its properties.

Also you should not read directly from it: https://github.com/sindresorhus/got/issues/223#issuecomment-405076226

Was this page helpful?
0 / 5 - 0 ratings

Related issues

quocnguyen picture quocnguyen  路  4Comments

dominusmars picture dominusmars  路  3Comments

lukechu10 picture lukechu10  路  3Comments

sindresorhus picture sindresorhus  路  3Comments

carvallegro picture carvallegro  路  4Comments