0

I have to collect multiple "data" events using http.get() and append them to a string and print it to the console. The last two console.log() statements always print 0 and an empty string. But the console.log() inside the http.get() prints all the received data correctly. The string str is a global variable so no scope problems. Then why does the last line print an empty string?

// JavaScript File
var http = require('http');

var str = '';

http.get(process.argv[2], function(response){
    response.on('error', console.error);
    response.on('data', function(data){
       str += data.toString();
    });
    response.on('end', function(){
        console.log(str); //works fine, prints the received data
    );
}).on('error', console.error);

console.log(str.length); // prints 0
console.log(str); // prints empty string
Sid24
  • 334
  • 3
  • 14
  • 1
    This is asynchronous java script .. meaning your JavaScript doesn't wait for your previous function to complete . It executes the next statement asynchronously . I would suggest use a call back after your response completes like the one you already have .. but if you want that value outside of ur http get . Consider using promises – karthik006 Jul 01 '17 at 17:55
  • Possible duplicate of [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) – tiagodws Jul 01 '17 at 18:00

1 Answers1

1

This is a common gotcha when working with node. You are dealing with an asynchronous request when you use http.get(). What this means is you final console.log() statement will be called before the callback functions within http.get().

With your code the order of events goes something like this:

  • define str
  • initiate http.get()
  • final two console.log() statements
  • receive data from http.get()
  • add to str
  • console.log() inside the http.get() callbacks

So everything is working, you are just asking for the data before you have received it.

Mark
  • 90,562
  • 7
  • 108
  • 148