Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Node.js dns Module

Node.js dns Module

Java FileNode.js Built-in Modules


Node.js's dns This module is a core module for Domain Name System (DNS) queries. DNS (Domain Name System) is the system that converts human-readable domain names (such as www.example.com) into machine-readable IP addresses (such as 192.0.2.1).

Why the dns Module Is Needed

In network communication, computers actually identify each other by IP addresses, but people find it easier to remember domain names than numeric IP addresses.dns The module provides the ability to perform domain name resolution in Node.js applications, enabling developers to:


Basic Usage of the dns Module

Importing the dns Module

To use dns module, you first need to import it:

const

dns

=

require

(

'dns'

)

;

Basic Resolution Methods

dns The module provides multiple resolution methods, the most commonly used being lookup and resolve。

dns.lookup()

dns.lookup() is the simplest domain name resolution method; it uses functionality provided by the operating system to perform DNS queries:

Example

dns.

lookup

(

'example.com'

,

(

err

,

address

,

family

)

=>

{

 

if

(

err

)

throw

err

;

  console.

log

(

`Address

:

$

{

address

}

,

IP Version

:

IPv$

{

family

}

`

)

;

}

)

;

dns.resolve()

dns.resolve() provides finer-grained control, allowing you to query specific types of DNS records:

Example

dns.

resolve

(

'example.com'

,

'A'

,

(

err

,

addresses

)

=>

{

 

if

(

err

)

throw

err

;

  console.

log

(

`A Record

:

$

{

JSON.

stringify

(

addresses

)

}

`

)

;

}

)

;


Main Methods of the dns Module

Forward Resolution

Forward resolution is the process of resolving a domain name into an IP address:

Example

dns.

resolve4

(

'google.com'

,

(

err

,

addresses

)

=>

{

 

if

(

err

)

throw

err

;

  console.

log

(

`IPv4 Address

:

$

{

addresses

}

`

)

;

}

)

;

dns.

resolve6

(

'google.com'

,

(

err

,

addresses

)

=>

{

 

if

(

err

)

throw

err

;

  console.

log

(

`IPv6 Address

:

$

{

addresses

}

`

)

;

}

)

;

Reverse resolution

Reverse resolution is the process of resolving an IP address into a domain name:

Example

dns.

reverse

(

'8.8.8.8'

,

(

err

,

hostnames

)

=>

{

 

if

(

err

)

throw

err

;

  console.

log

(

`Reverse Resolution Result

:

$

{

hostnames

}

`

)

;

}

)

;

Other DNS Record Queries

dns The module also supports querying other types of DNS records:

Example

// MX record (Mail Exchange record)

dns.

resolveMx

(

'google.com'

,

(

err

,

addresses

)

=>

{

 

if

(

err

)

throw

err

;

  console.

log

(

`MX Record

:

$

{

JSON.

stringify

(

addresses

)

}

`

)

;

}

)

;

// TXT record (Text record)

dns.

resolveTxt

(

'google.com'

,

(

err

,

records

)

=>

{

 

if

(

err

)

throw

err

;

  console.

log

(

`TXT Record

:

$

{

JSON.

stringify

(

records

)

}

`

)

;

}

)

;


Synchronous and Asynchronous Methods

Asynchronous methods

By default,dns The module's methods are asynchronous and use callback functions to handle results:

Example

dns.

lookup

(

'nodejs.org'

,

(

err

,

address

,

family

)

=>

{

  console.

log

(

'Async Result:'

,

address

)

;

}

)

;

Promise Version

Starting from Node.js v10.6.0,dns the module's methods also provide Promise-based versions:

Example

const

{

promises

:

dnsPromises

}

=

require

(

'dns'

)

;

async

function

lookupExample

(

)

{

 

try

{

   

const

result

=

await dnsPromises.

lookup

(

'nodejs.org'

)

;

    console.

log

(

'Promise Result:'

,

result.

address

)

;

 

}

catch

(

err

)

{

    console.

error

(

err

)

;

 

}

}

lookupExample

(

)

;


Error handling

DNS queries may fail, so handling errors correctly is very important:

Example

dns.

lookup

(

'nonexistent.example.com'

,

(

err

,

address

)

=>

{

 

if

(

err

)

{

   

if

(

err.

code

===

'ENOTFOUND'

)

{

      console.

log

(

'Domain does not exist'

)

;

   

}

else

{

      console.

log

(

'Unknown error:'

,

err

)

;

   

}

   

return

;

 

}

  console.

log

(

'Address:'

,

address

)

;

}

)

;

Common DNS error codes include:


Practical Application Examples

Check Whether a Domain Name Is Resolvable

Example

function

isDomainResolvable

(

domain

)

{

 

return

new

Promise

(

(

resolve

)

=>

{

    dns.

lookup

(

domain

,

(

err

)

=>

{

      resolve

(

!

err

)

;

   

}

)

;

 

}

)

;

}

isDomainResolvable

(

'google.com'

)

.

then

(

result

=>

{

  console.

log

(

'Domain is resolvable:'

,

result

)

;

}

)

;

Resolve Domain Names in Bulk

Example

const

domains

=

[

'google.com'

,

'facebook.com'

,

'twitter.com'

]

;

Promise.

all

(

domains.

map

(

domain

=>

dnsPromises.

lookup

(

domain

)

)

)

  .

then

(

results

=>

{

    results.

forEach

(

(

result

,

index

)

=>

{

      console.

log

(

`$

{

domains

[

index

]

}

=>

$

{

result.

address

}

`

)

;

   

}

)

;

 

}

)

  .

catch

(

err

=>

{

    console.

error

(

'Resolution failed:'

,

err

)

;

 

}

)

;


Performance considerations

DNS queries are I/O operations and may affect application performance:

  1. Cache Results: For frequently queried domain names, consider caching results at the application layer
  2. Concurrency Limits: Avoid launching a large number of DNS queries at the same time
  3. Timeout Settings: Set reasonable timeout values for DNS queries

Example

const

cache

=

new

Map

(

)

;

async

function

cachedLookup

(

domain

)

{

 

if

(

cache.

has

(

domain

)

)

{

   

return

cache.

get

(

domain

)

;

 

}

 

 

const

result

=

await dnsPromises.

lookup

(

domain

)

;

  cache.

set

(

domain

,

result

)

;

 

return

result

;

}



Method

Method Description Example
dns.lookup(hostname[, options], callback) Resolves a hostname to the first IPv4 or IPv6 address. The optional parameter options is used to specify the resolution method, such as family(4 or 6). dns.lookup('example.com', (err, address) => {});
dns.resolve(hostname[, rrtype], callback) Queries DNS records of a specified record type, returning A records by default. Supported types include A, AAAA, MX, TXT, etc. dns.resolve('example.com', 'MX', (err, addresses) => {});
dns.resolve4(hostname, callback) Queries the IPv4 address of a hostname. dns.resolve4('example.com', (err, addresses) => {});
dns.resolve6(hostname, callback) Queries the IPv6 address of a hostname. dns.resolve6('example.com', (err, addresses) => {});
dns.resolveMx(hostname, callback) Queries the MX (Mail Exchange) records of a hostname. dns.resolveMx('example.com', (err, addresses) => {});
dns.resolveTxt(hostname, callback) Queries the TXT (Text) records of a hostname. dns.resolveTxt('example.com', (err, records) => {});
dns.reverse(ip, callback) Resolves an IP address to a hostname. dns.reverse('8.8.8.8', (err, hostnames) => {});
dns.getServers() Returns an array of the current DNS servers. console.log(dns.getServers());
dns.setServers(servers) Sets a custom array of DNS servers. dns.setServers(['8.8.8.8', '8.8.4.4']);

rrtypes

The following lists the valid rrtypes values in the dns.resolve() method:


Error Codes

Each DNS query may return the following error codes:

Example

The following are examples of some common dns module methods, showing how to query a host's IP address, obtain DNS records, and more.

** 1. Using dns.lookup() to Get an IP Address**

Example

const

dns

=

require

(

'dns'

)

;

// Look up the IPv4 address of a domain name

dns.

lookup

(

'runoob.com'

,

(

err

,

address

,

family

)

=>

{

 

if

(

err

)

throw

err

;

  console.

log

(

`IP Address

:

$

{

address

}

,

Address Family

:

IPv$

{

family

}

`

)

;

}

)

;

dns.lookup() is a simplified interface that finds the first IPv4 or IPv6 address for the specified hostname.

2. Using dns.resolve() to Query Different Types of DNS Records

Example

const

dns

=

require

(

'dns'

)

;

// Query MX records

dns.

resolve

(

'example.com'

,

'MX'

,

(

err

,

addresses

)

=>

{

 

if

(

err

)

throw

err

;

  console.

log

(

'MX Records:'

,

addresses

)

;

}

)

;

// Query TXT records

dns.

resolve

(

'example.com'

,

'TXT'

,

(

err

,

records

)

=>

{

 

if

(

err

)

throw

err

;

  console.

log

(

'TXT Records:'

,

records

)

;

}

)

;

With dns.resolve(), you can specify a record type (such as MX, TXT, etc.) to query different DNS records.

3. Using dns.reverse() for Reverse DNS Queries

Example

const

dns

=

require

(

'dns'

)

;

// Reverse-resolve an IP address to a hostname

dns.

reverse

(

'8.8.8.8'

,

(

err

,

hostnames

)

=>

{

 

if

(

err

)

throw

err

;

  console.

log

(

`Hostname of 8.8.8.8

:

$

{

hostnames

}

`

)

;

}

)

;

Reverse resolution resolves an IP address into a domain name and is often used to check the matching relationship between a domain name and an IP address.

** 4. Getting and Setting DNS Servers**

Example

const

dns

=

require

(

'dns'

)

;

// Get the current list of DNS servers

console.

log

(

'Current DNS Servers:'

,

dns.

getServers

(

)

)

;

// Set custom DNS servers

dns.

setServers

(

[

'1.1.1.1'

,

'8.8.8.8'

]

)

;

console.

log

(

'New DNS Servers:'

,

dns.

getServers

(

)

)

;

With dns.getServers() you can get the list of DNS servers configured in the current system, and dns.setServers() lets you customize DNS servers so that a specific DNS resolution service is used for queries.

Asynchronous and Synchronous Methods

Practical Application Scenarios

dns The module enables Node.js applications to perform domain name resolution and DNS queries, allowing greater flexibility when handling network communication. Through asynchronous interfaces, DNS queries can be completed efficiently without blocking the main thread.

Java FileNode.js Built-in Modules