Nodejs accessing variable

In node js i cannot access variable op outside the function. I also declared it outside the function, but still I cannot access it... kindly help me... You can run the code and check. I have two console.logs. But only inside function log works.

Working code in editor,

http://goo.gl/NZ4LBQ

var http = require('http');
console.log("hi")var options ={
    host:'api.usergrid.com',
    path:'/siddharth1/sandbox/restaurants'};var op =[];//declaring outside functionvar req = http.get(options,function(res){
    console.log('STATUS: '+ res.statusCode);
    console.log('HEADERS: '+ JSON.stringify(res.headers));// Buffer the body entirely for processing as a whole.var bodyChunks =[];
    res.on('data',function(chunk){// You can process streamed parts here...
        bodyChunks.push(chunk);}).on('end',function(){var body =Buffer.concat(bodyChunks);
        console.log('BODY: '+ body);// ...and/or process the entire body here.var body2 = JSON.parse(body);

        op = body2.entities.map(function(item){return item.name;});
        console.log(op);// only this works})});

req.on('error',function(e){
    console.log('ERROR: '+ e.message);});
console.log("outside function "+ op);//this doesnt work
console.log('Server listening on port 80');
0 3 124
3 REPLIES 3

Your outside log call is getting hit before the request returns due to async. This is a pretty decent writeup that explains why and provides suggestions on how to do what you want, I believe: http://justinklemm.com/node-js-async-tutorial/

So I should be using a async.each() right?

I can't really answer that without knowing what you are trying to do. The async module is one way to avoid what they call "callback hell" .. but you don't have to use it. You could just include whatever logic you want to do with the response in the callback function.