get ip address by domain with dns.lookup() node.js
You can not because dns.lookup() function is working async.
Though the call to dns.lookup() will be asynchronous from JavaScript's perspective, it is implemented as a synchronous call to getaddrinfo(3) that runs on libuv's threadpool. This can have surprising negative performance implications for some applications, see the UV_THREADPOOL_SIZE documentation for more information.
There are different ways to take the result. Welcome to JS world!
Callback
dns.lookup("www.aWebSiteName.am", (err, address, family) => {
if(err) throw err;
printResult(address);
});
function printResult(address){
console.log(address);
}
Promise
const lookupPromise = new Promise((resolve, reject) => {
dns.lookup("www.aWebSiteName.am", (err, address, family) => {
if(err) reject(err);
resolve(address);
});
});
lookupPromise().then(res => console.log(res)).catch(err => console.error(err));
Promise async/await
async function lookupPromise(){
return new Promise((resolve, reject) => {
dns.lookup("www.aWebSiteName.am", (err, address, family) => {
if(err) reject(err);
resolve(address);
});
});
};
try{
cons address = await lookupPromise();
}catch(err){
console.error(err);
}
This is normal because "dns.lookup" is executed asynchronously
So you can't just use the returned value of the function
You need to do your logic inside the callback or make an helper to promisfy the function and execute it in async function with await.
Something like this:
function lookup(domain) {
return new Promise((resolve, reject) => {
dns.lookup(address, (err, address, family) => {
if (err) {
reject(err)
} else {
resolve({ address, family })
}
})
})
}
async function test() {
let ipAddress = await lookup(("www.aWebSiteName.am");
}
EDIT:
You can also use:
const dns = require('dns');
dnsPromises = dns.promises;
async function test() {
let data = await dnsPromises.lookup(("www.aWebSiteName.am");
}