Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the whole response body when the response is chunked?

Tags:

http

node.js

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?

like image 418
ajsie Avatar asked Feb 22 '11 21:02

ajsie


2 Answers

request.on('response', function (response) {
  var body = '';
  response.on('data', function (chunk) {
    body += chunk;
  });
  response.on('end', function () {
    console.log('BODY: ' + body);
  });
});
request.end();
like image 148
Pero P. Avatar answered Oct 25 '22 10:10

Pero P.


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.

like image 27
Jim Danz Avatar answered Oct 25 '22 09:10

Jim Danz