Node.js – dnsPromises.lookup() Method


The dnsPromises.lookup() method resolves the hostname (e.g., tutorialspoint.com) into the first found A IPv4) or AAAA (IPv6) record. The properties available under the options are optional.

dns.lookup() does not have anything to do with the DNS protocol. The implementation uses an OS facility that can associate names with addresses and vice versa.

The difference between the dnsPromises and dns module is that dns.promises provides an alternative way to asynchronous DNS methods that return Promise objects instead of callbacks.

Syntax

dnsPromises.lookup(hostname, [options])

Parameters

  • hostname – This is the website hostname for which you want to look up the DNS values.

  • options – It can have the following options

    • family – It can have the value 4, 6 or 0 only. The value 0 indicates that both the IPv4 and IPv6 addresses are returned.

    • hints – It enables one or more getAddrinfoflags.

    • all – The callback returns all the resolved addresses in an array when this value is set to True, else a single address is returned.

    • verbatim – The callback is returned in the same order the DNS resolver returned them when set to True.

Example 1

Create a file "lookup.js" and copy the following code snippet. After creating the file, use the command "node lookup.js" to run this code.

// dns.lookup() method Demo Example
// Importing the dns module
const dns = require('dns');

const dnsPromises = dns.promises;

// Passing some options for dns.lookup()
const options = {
   family: 6,
   hints: dns.ADDRCONFIG | dns.V4MAPPED,
};

// Result will be an array, when all the options are true
dnsPromises.lookup('tutorialspoint.com', options).then((response) =>
{
   console.log('addresses: %j', response);
});

Output

C:\home
ode>> node lookup.js addresses: {"address":"64:ff9b::5fd9:4a92","family":6}

Example 2

// dns.lookup() method Demo Example

// Importing the dns module
const dns = require('dns');
const dnsPromises = dns.promises;

// Setting options for dnsPromises.lookup()
// method, all as true
const options = {
   all:true,
};

// Result will be an array, when all the options are true
dnsPromises.lookup('tutorialspoint.com', options).then((response) =>
{
   console.log('addresses: %j', response);
});

Output

C:\home
ode>> node lookup.js addresses: [{"address":"95.217.74.146","family":4},{"address":"64:ff9b::5fd9 :4a92","family":6}]

Updated on: 29-Oct-2021

56 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements