Categories
JavaScript Answers

How to get the whole response body when the response is chunked in Node.js?

Spread the love

Sometimes, we want to get the whole response body when the response is chunked in Node.js.

In this article, we’ll look at how to get the whole response body when the response is chunked in Node.js.

How to get the whole response body when the response is chunked in Node.js?

To get the whole response body when the response is chunked in Node.js, we an listen to the on and end events.

For instance, we write

request.on("response", (response) => {
  let body = "";
  response.on("data", (chunk) => {
    body += chunk;
  });
  response.on("end", () => {
    console.log(body);
  });
});
request.end();

to call request.on with 'response' to listen for the response.

Then we call response.on with 'data' to listen for the response chunks and append them to body.

Next, we listen to the end event with a callback that runs when we got the whole response, so we log the full response body in the callback.

Conclusion

To get the whole response body when the response is chunked in Node.js, we an listen to the on and end events.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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