简体   繁体   中英

NodeJs: Collecting data across multiple “data” events using http.get()

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM