Ajay P.
Ajay P.

Reputation: 495

External IP is not accessible outside the function in Node js

I am new here. I am trying to get external IP using a package named "external-ip" They have this code in their example

const getIP = require('external-ip')(); 
getIP((err, ip) => {
          if (err) {
              // every service in the list has failed
              throw err;
          }
          ip = ip;
          console.log(ip);
});

It is working perfectly however I want to use IP outside the function may I know how can I use it ?

I tried this but didnt work for me

const ipaddress = getIP((err, ip) => {
          if (err) {
              // every service in the list has failed
              throw err;
          }
          return ip;
          console.log(ip);
});

console.log(ipaddress);

Upvotes: 0

Views: 134

Answers (2)

maestro.inc
maestro.inc

Reputation: 815

First define ip with let

ip is defined under the local scope of your program which means it is only accessible within your function. Now you should avoid using global scope as much as possible as that is generally considered bad practice but that is one way to have the ip varaible accessible from anywhere in your program. The other way would be to return it

const getIP = require('external-ip')(); 
const ipaddress = getIP((err, ip) => {
          if (err) {
              // every service in the list has failed
              throw err;
          }
          console.log(ip);
          return ip;
});

let ip = ipaddress()
console.log(ip)

Note that anything after the return statement is a dead code and will not run so any code you want to run should be placed before any return statement(notice the position of the console.log() in the function

Upvotes: 1

Ajay P.
Ajay P.

Reputation: 495

This will work

let ipaddress;
getIP((err, ip) => {
          if (err) {
              // every service in the list has failed
              throw err;
          }
          ipaddress = ip;
});

console.log(ipaddress);

Solution by Edgar Cuarezma

Upvotes: 0

Related Questions