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,
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');