0

I would like to set a global variable and set it value from inside of node.js request module get function. Here is my code -

var req = require('request');
var server = '';

req.get('http://httpbin.org/headers',function(err,res,body){
server = res.headers.server;
console.log(body);
});

console.log(server); // result undefined

Problem is everytime I get undefined.

hayes robin
  • 43
  • 2
  • 7
  • Yes, inside get function , console.log(server) and console.log(res.headers.server) are working ! – hayes robin Jun 25 '16 at 10:40
  • 1
    The problem with your code is that you print the `server` immediately, but the callback function will be called only when the request is finished which could be miliseconds or even seconds after you print your variable. What do you want to achieve? You should show some more code. – vsakos Jun 25 '16 at 10:50
  • Hi @vsakos , I am studying nodejs request package to learn How can I get any value from response header or cookies and then push into a global variable to use with another request. – hayes robin Jun 25 '16 at 10:54
  • That's not how it works. Node is async, which means when you run an async function, it returns immediately, doesn't wait for the callback function to be called. If you want to use the data you get from one request right after it finishes, you can either start another request from the callback of the first one or use promises to avoid the _callback hell_. – vsakos Jun 25 '16 at 11:04

1 Answers1

-1

It's not recommended you set global in a callback. It's better you use events for this

EDIT

app.on('serverHeader', function(data){
//do stuff
});

app.get('...', function(req, res, cb){
app.emit('serverHeader', res.headers);
});
Ebrahim Pasbani
  • 9,168
  • 2
  • 23
  • 30