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

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.