0

Question linked to Get local IP address in node.js

May I ask for a little help?

In this example of usage,

getNetworkIP(function (error, ip) {
console.log(ip);
if (error) {
    console.log('error:', error);
}}, false);

how is it possible to get the ip value outside the callback? For instance to use it for a connection or whatever. I tried to return it, export it, pass it, but non of these methods are working. Please help me, I'm going mental!!

Thanks!

P.S.: this code has been really useful to me, to understand a little bit more. I'm really newbie. Thanks a million for sharing it.

Community
  • 1
  • 1
  • Answers are not the way to post follow up questions. You should create a new question and link to this. In any case, the call is asynchronous, that means the next statement will run before the call is finished, so no you cannot access ip somewhere else unless you set a global variable from your callback – Juan Mendes – Jacques Clementi Aug 05 '11 at 23:20
  • Sorry for the answer as a question. I'll ask a new question and link. Can you give an example of setting local variable in this case? I tries and it says undefined or null when I printed it. It seems to me that it's impossible to get out of the exec function. Thanks – Jacques Clementi Aug 05 '11 at 23:21

1 Answers1

0

As Juan Mendes tried to tell you the call you are making is async. Which means that node will continue executing code and then get the callback. Whatever you need to do with your IP you can do it either inside your callback or you can save it as a global variable.

var myIP = '';

getNetworkIP(function (error, ip) {
    if (error) {
        console.log('error:', error);
    }else{
        myIP = ip;
        MyFunctionToConnectTo(myIP);
    }
}, false);
Marcus Granström
  • 17,816
  • 1
  • 22
  • 21
  • Thanks guys. I really get it now. What I was missing was that the callback function could be placed anyway I need it. Hence, it's easy to call as callback the function I need. – Jacques Clementi Aug 06 '11 at 23:10