0

When I make a http request, I need to concatenate the response:

request.on('response', function (response) {
var body = '';
response.on('data', function (chunk) {
    body += chunk;
    });
...

Why was that implemented this way? Why not output the whole result?

Renaro Santos
  • 403
  • 1
  • 7
  • 19

2 Answers2

1

Node only uses a single process, no thread. This mean that if spend a lot of time doing something you can´t process other things, like for example other client requests...

For that reason when you are coding in node, you need code thinking in async way.

In this scenario, the request could be slowly, and the program will wait for this request doing nothing.

I found this: Why is node.js asynchronous?

And this is so interesting as well: http://en.wikipedia.org/wiki/Read%E2%80%93eval%E2%80%93print_loop

Community
  • 1
  • 1
Raúl Martín
  • 4,471
  • 3
  • 23
  • 42
1

What you're getting back is a stream, which is a very handy construct in node.js. Required reading: https://github.com/substack/stream-handbook

If you want to wait until you've received the whole response, you can do this very easily:

var concat = require('concat-stream');

request.on('response', function(response) {
    response.pipe(concat(function(body) {
        console.log(body);
    }));
});
Andrew Lavers
  • 8,023
  • 1
  • 33
  • 50