Get the whole response body when the response is chunked?


Question

I'm making a HTTP request and listen for "data":

response.on("data", function (data) { ... })

The problem is that the response is chunked so the "data" is just a piece of the body sent back.

How do I get the whole body sent back?

1
51
2/22/2011 9:24:53 PM

Accepted Answer

request.on('response', function (response) {
  var body = '';
  response.on('data', function (chunk) {
    body += chunk;
  });
  response.on('end', function () {
    console.log('BODY: ' + body);
  });
});
request.end();
70
2/22/2011 9:15:49 PM

Over at https://groups.google.com/forum/?fromgroups=#!topic/nodejs/75gfvfg6xuc, Tane Piper provides a good solution very similar to scriptfromscratch's, but for the case of a JSON response:

  request.on('response',function(response){
     var data = [];
     response.on('data', function(chunk) {
       data.push(chunk);
     });
     response.on('end', function() {
       var result = JSON.parse(data.join(''))
       return result
     });
   });`

This addresses the issue that OP brought up in the comments section of scriptfromscratch's answer.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon