1

I recently started to programming javascript on server side(node js), and i have a really simple trouble, that i can't solve :S

I want to download a txt file, and save it as a string variable. This is my atempt:

var consensus;
http.get('random/url/consensus.txt' , function(res) {
        res.on('data', function (chunk) {
        consensus = ('BODY: ' + chunk);});
    });
console.log(consensus)

When i run the script it said "consensus" is undefined, but when i change consensus = ('BODY: ' + chunk);}); this line to this console.log('BODY: ' + chunk);}); its print out the string (file) that i want to save as string. Ohh before i forget to mention, I want to find a solution only with the standard libs.

Syngularity
  • 795
  • 3
  • 17
  • 42

1 Answers1

2

Your console.log is OUTSIDE the callback, therefor it gets called right after you initiate the call before the callback is happening.

Try doing something like this: (I am not so sure on the events names)

var req = http.get(......) //rest of code stays the same

req.on('end', function() {console.log(consensus);});

I think it should solve your problems.

And try to read more about the async nature of nodeJS.

PiniH
  • 1,901
  • 13
  • 20