How do I store the return value of dns.lookup in a variable? If I store it in an array it shows blank.
Following is the code I'm working on:
const dns = require('dns');
class Network
{
search(host)
{
let options = {
hints: dns.ADDRCONFIG | dns.V4MAPPED,
all: true,
verbatim: true
}
let addr = [];
dns.lookup(host, options, (error, address) =>
{
if(error)
{
console.log("Could not resolve %s\n", host);
console.log(error);
}
address.forEach(ip => {
addr.push({
address: ip.address,
family: ip.family
});
});
});
console.log(addr);
return addr;
}
}
const network = new Network();
let output = network.search("www.google.com");
console.log(output);
The output of the code is Blank ie []
Please suggest a rememdy.
Thanks
The last parameter to dns.lookup
must be a callback as you have already noticed. The method is asynchronous but this line return addr;
is not - addr is returned before getting populated. The method definition of search
could be changed to take as second parameter a callback that will be called with the result of dns.lookup
. Something like this:
search(host, done) {
...
dns.lookup(host, options, (err, addresses) => {
...
const finalAddresses = [];
addresses.forEach((ip) => {
finalAddresses.push({
address: ip.address,
family: ip.family
});
});
done(null, finalAddresses);
});
}
const network = new Network();
network.search("www.google.com", (err, result) => {
if (err) {
return console.log(err);
}
console.log(result);
});
I would suggest using the async/await syntax along with the very useful util.promisify function.
This gives us code that is more compact, it will also allow you to write your code in a way that's very similar to synchronous code.
We'll then use some destructuring to pick only the properties in the address object(s) we're interested in.
const dns = require('dns');
const promisify = require('util').promisify;
class Network
{
async search(host)
{
let options = {
hints: dns.ADDRCONFIG | dns.VMAPPED,
all: true,
verbatim: true
}
let address = await promisify(dns.lookup)(host, options);
return address.map( ({address, family}) => {
return { address, family };
});
}
}
async function testSearch() {
const network = new Network();
let output = await network.search("www.google.com");
console.log(output);
}
testSearch();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.