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