Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get data out of a Node.js http get request

I'm trying to get my function to return the http get request, however, whatever I do it seems to get lost in the ?scope?. I'm quit new to Node.js so any help would be appreciated

function getData(){   var http = require('http');   var str = '';    var options = {         host: 'www.random.org',         path: '/integers/?num=1&min=1&max=10&col=1&base=10&format=plain&rnd=new'   };    callback = function(response) {          response.on('data', function (chunk) {               str += chunk;         });          response.on('end', function () {               console.log(str);         });          //return str;   }    var req = http.request(options, callback).end();    // These just return undefined and empty   console.log(req.data);   console.log(str); } 
like image 244
Daryl Rodrigo Avatar asked Oct 23 '13 10:10

Daryl Rodrigo


1 Answers

Of course your logs return undefined : you log before the request is done. The problem isn't scope but asynchronicity.

http.request is asynchronous, that's why it takes a callback as parameter. Do what you have to do in the callback (the one you pass to response.end):

callback = function(response) {    response.on('data', function (chunk) {     str += chunk;   });    response.on('end', function () {     console.log(req.data);     console.log(str);     // your code here if you want to use the results !   }); }  var req = http.request(options, callback).end(); 
like image 87
Denys Séguret Avatar answered Oct 02 '22 04:10

Denys Séguret