Node.js dns Module

Java FileNode.js built-in modules


Node.js'sdnsmodule is a core module for Domain Name System (DNS) queries. DNS (Domain Name System) is a system that converts human-readable domain names (such aswww.example.com) into machine-readable IP addresses (such as192.0.2.1).

Why do you need the dns module

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

  • Resolve domain names to IP addresses
  • Reverse-resolve IP addresses to domain names
  • Query DNS records (MX, TXT, SRV, etc.)

Basic usage of the dns module

Importing the dns module

To use thednsmodule, you first need to import it:

const dns = require('dns');

Basic resolution methods

dnsThe module provides several resolution methods. The most commonly used islookupandresolve。

dns.lookup()

dns.lookup()is the simplest domain resolution method. It uses the 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 and can 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}`);
});

Querying other DNS records

dnsThe 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,dnsthe module's methods are asynchronous and use callback functions to handle results:

Example

dns.lookup('nodejs.org', (err, address, family) => {
  console.log('Asynchronous result:', address);
});

Promise version

Starting from Node.js v10.6.0,dnsthe 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:

  • ENOTFOUND: domain does not exist
  • ESERVFAIL: DNS server returned failure
  • ETIMEOUT: DNS query timed out

Practical application examples

Check whether a domain can be resolved

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);
});

Batch resolve domain names

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 domains, consider caching results at the application layer
  2. Concurrency limits: Avoid making a large number of DNS queries at the same time
  3. Timeout settings: Set a reasonable timeout 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

MethodDescriptionExample
dns.lookup(hostname[, options], callback)Resolves a hostname to the first IPv4 or IPv6 address. The optional parameteroptionsis used to specify the resolution method, such asfamily(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 addresses of a hostname.dns.resolve4('example.com', (err, addresses) => {});
dns.resolve6(hostname, callback)Queries the IPv6 addresses 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:

  • 'A'IPv4 address, default
  • 'AAAA'IPv6 address
  • 'MX'Mail exchange records
  • 'TXT'text records
  • 'SRV'SRV records
  • 'PTR'Used for reverse IP lookup
  • 'NS'Domain name server records
  • 'CNAME'Alias records
  • 'SOA'Initial value of the authoritative record

Error codes

Each DNS query may return the following error codes:

  • dns.NODATA: No data response.
  • dns.FORMERR: Query format error.
  • dns.SERVFAIL: General failure.
  • dns.NOTFOUND: Domain name not found.
  • dns.NOTIMP: The requested operation is not implemented.
  • dns.REFUSED: Query refused.
  • dns.BADQUERY: Query format error.
  • dns.BADNAME: Domain name format error.
  • dns.BADFAMILY: Address protocol not supported.
  • dns.BADRESP: Reply format error.
  • dns.CONNREFUSED: Unable to connect to DNS server.
  • dns.TIMEOUT: Timeout connecting to DNS server.
  • dns.EOF: End of file.
  • dns.FILE: File read error.
  • dns.NOMEM: Memory overflow.
  • dns.DESTRUCTION: Channel destroyed.
  • dns.BADSTR: String format error.
  • dns.BADFLAGS: Illegal identifier.
  • dns.NONAME: The given host is not numeric.
  • dns.BADHINTS: Illegal HINTS identifier.
  • dns.NOTINITIALIZED: The c-ares library has not been initialized.
  • dns.LOADIPHLPAPI: Error loading iphlpapi.dll.
  • dns.ADDRGETNETWORKPARAMS: Unable to find the GetNetworkParams function.
  • dns.CANCELLED: DNS query canceled.

Example

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

1. Use dns.lookup() to get an IP address

Example

const dns = require('dns');

// Look up the IPv4 address of a domain
dns.lookup('example.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. Use 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);
});

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

3. Use dns.reverse() for reverse DNS query

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 to a domain name, often used to check the matching relationship between a domain name and an IP address.

4. Get and set DNS servers

Example

const dns = require('dns');

// Get the current DNS server list
console.log('Current DNS servers:', dns.getServers());

// Set a custom DNS server
dns.setServers(['1.1.1.1', '8.8.8.8']);
console.log('New DNS server:', dns.getServers());

With dns.getServers(), you can obtain the list of DNS servers currently configured on the system. dns.setServers() allows you to set custom DNS servers, so that specific DNS resolution services can be used for queries.

Asynchronous and synchronous methods

  • Asynchronous methods: such asdns.lookup()、dns.resolve()etc., non-blocking, suitable for concurrent tasks.
  • Synchronous methods: such asdns.lookupSync()、dns.resolve4Sync(), blocking, suitable for small-scale use, avoid using in high-concurrency scenarios.

Practical application scenarios

  • Domain name resolution for web applications: Query the IP address of a domain name on the server to fetch web pages or resources.
  • Mail server configuration check: Verify the correctness of mail server configuration through MX records.
  • Anti-spam: Through reverse DNS query, detect whether the server sending emails matches the domain name, thereby identifying the source of spam.
  • Load balancing: By resolving the different IP addresses of a domain name, create a load balancing scheme to distribute traffic to multiple servers.

dnsThe module enables Node.js applications to perform domain name resolution and DNS queries, giving them more flexibility in handling network communications. Through asynchronous interfaces, DNS queries can be completed efficiently without blocking the main thread.

Java FileNode.js built-in modules

Other extensions