DNS Module in Node.js: Name Resolution and Networking

The node:dns module provides name resolution capabilities in Node.js. . It allows developers to look up IP addresses for hostnames and perform DNS queries. While dns.lookup() uses the operating system’s facilities (and may not involve actual DNS protocol communication), other functions such as dns.resolve4() or dns.reverse() directly query DNS servers. The module also provides the dns.Resolver class for creating independent resolvers with custom server configurations.

dns.lookup()dns.resolve()dns.Resolver classgetServers / setServersreverse DNS lookups

~6 min read · Updated Dec 27, 2025

1. Introduction


The node:dns module enables hostname resolution. It can be used to look up IP addresses and perform DNS queries. While dns.lookup() relies on the operating system’s resolver, other functions directly query DNS servers.


2. dns.lookup()


dns.lookup() resolves a hostname into an IPv4 or IPv6 address using OS facilities.


const dns = require('node:dns');
dns.lookup('example.org', (err, address, family) => {
  console.log('address: %j family: IPv%s', address, family);
});

  • Options include family, hints, all, and order.
  • When all is true, returns an array of addresses.
  • Errors include ENOTFOUND when resolution fails.

3. DNS Queries


Other functions in the module perform actual DNS queries:


  • dns.resolve4(): Resolves A records (IPv4).
  • dns.resolve6(): Resolves AAAA records (IPv6).
  • dns.resolveMx(): Resolves mail exchange records.
  • dns.reverse(): Performs reverse lookups (IP → hostname).

dns.resolve4('archive.org', (err, addresses) => {
  addresses.forEach((a) => {
    dns.reverse(a, (err, hostnames) => {
      console.log(`reverse for ${a}: ${JSON.stringify(hostnames)}`);
    });
  });
});

4. dns.Resolver Class


The dns.Resolver class allows independent resolvers with custom server settings.


const { Resolver } = require('node:dns');
const resolver = new Resolver();
resolver.setServers(['4.4.4.4']);
resolver.resolve4('example.org', (err, addresses) => {
  console.log(addresses);
});

  • resolver.getServers(): Returns current DNS servers.
  • resolver.setServers(): Sets custom DNS servers.
  • resolver.cancel(): Cancels outstanding queries.
  • resolver.setLocalAddress(): Specifies outbound IP addresses.

5. dns.getServers()


Returns the array of IP addresses currently configured for DNS resolution:


console.log(dns.getServers());
// ['8.8.8.8', '2001:4860:4860::8888']

6. Example with Options


const options = { family: 6, hints: dns.ADDRCONFIG | dns.V4MAPPED };
dns.lookup('example.org', options, (err, address, family) =>
  console.log('address: %j family: IPv%s', address, family)
);

Conclusion


The node:dns module provides both OS-level name resolution and direct DNS queries. With dns.lookup(), developers can resolve hostnames the same way the operating system does, while functions like resolve4() and reverse() allow explicit DNS queries. The dns.Resolver class adds flexibility by enabling custom server configurations, making the module a powerful tool for networking applications in Node.js.


1. getaddrinfo Flags


Flags can be passed as hints to dns.lookup():


  • dns.ADDRCONFIG: Limits returned addresses to non-loopback types configured on the system.
  • dns.V4MAPPED: Returns IPv4-mapped IPv6 addresses if no IPv6 is found.
  • dns.ALL: With V4MAPPED, returns both IPv6 and IPv4-mapped IPv6 addresses.

2. dns.lookupService()


Resolves an IP address and port into a hostname and service:


dns.lookupService('127.0.0.1', 22, (err, hostname, service) => {
  console.log(hostname, service);
  // Output: localhost ssh
});

3. dns.resolve()


Resolves DNS records based on rrtype:


  • A: IPv4 addresses → dns.resolve4()
  • AAAA: IPv6 addresses → dns.resolve6()
  • CNAME: Canonical names → dns.resolveCname()
  • MX: Mail exchange records → dns.resolveMx()
  • NS: Name server records → dns.resolveNs()
  • TXT: Text records → dns.resolveTxt()
  • SOA: Start of authority records → dns.resolveSoa()
  • SRV: Service records → dns.resolveSrv()
  • TLSA: Certificate associations → dns.resolveTlsa()

4. Example: resolveAny()


Retrieve all record types:


dns.resolveAny('example.com', (err, records) => {
  console.log(records);
});

5. dns.reverse()


Performs reverse DNS lookups (IP → hostname):


dns.reverse('8.8.8.8', (err, hostnames) => {
  console.log(hostnames);
});

6. Managing Result Order


  • dns.setDefaultResultOrder(order): Sets default order (ipv4first, ipv6first, verbatim).
  • dns.getDefaultResultOrder(): Retrieves current default order.

7. dnsPromises API


The Promises-based API provides modern asynchronous DNS methods:


const dnsPromises = require('node:dns').promises;
(async function() {
  const result = await dnsPromises.lookup('example.org', { family: 6 });
  console.log(result);
})();

  • dnsPromises.lookup(): Promise-based hostname resolution.
  • dnsPromises.resolve4(): Resolves A records.
  • dnsPromises.resolveMx(): Resolves MX records.
  • dnsPromises.reverse(): Reverse DNS lookups.

Conclusion


The node:dns module offers advanced tools for DNS record management, result ordering, and Promises-based asynchronous operations. These features enable developers to build more precise and flexible networking applications in Node.js.


1. dnsPromises.resolve()


This method resolves a hostname into DNS records. The record type is specified by the rrtype parameter.


  • A: IPv4 addresses → dnsPromises.resolve4()
  • AAAA: IPv6 addresses → dnsPromises.resolve6()
  • ANY: All records → dnsPromises.resolveAny()
  • CNAME: Canonical names → dnsPromises.resolveCname()
  • MX: Mail exchange records → dnsPromises.resolveMx()
  • NS: Name server records → dnsPromises.resolveNs()
  • PTR: Pointer records → dnsPromises.resolvePtr()
  • SOA: Start of authority records → dnsPromises.resolveSoa()
  • SRV: Service records → dnsPromises.resolveSrv()
  • TLSA: Certificate associations → dnsPromises.resolveTlsa()
  • TXT: Text records → dnsPromises.resolveTxt()

On success, the Promise resolves with an array of records. On error, the Promise rejects with an Error object containing err.code.


2. dnsPromises.resolve4()


This method resolves A records (IPv4 addresses) for a hostname.


  • hostname: The hostname to resolve.
  • options.ttl: When true, returns TTL values along with addresses.

const dnsPromises = require('node:dns').promises;

(async function() {
  const addresses = await dnsPromises.resolve4('example.org');
  console.log(addresses);
  // Output: ['74.125.79.104', '74.125.79.105', '74.125.79.106']
})();

If the ttl option is enabled:


const addresses = await dnsPromises.resolve4('example.org', { ttl: true });
console.log(addresses);
// Output: [{ address: '74.125.79.104', ttl: 60 }, ...]

3. Use Cases


  • Retrieve IPv4 and IPv6 addresses for network connections.
  • Query MX records for email servers.
  • Check TXT records for SPF or DKIM configurations.
  • Manage SOA and SRV records for specialized services.

Conclusion


The dnsPromises.resolve() and dnsPromises.resolve4() methods are powerful tools for working with DNS records in Node.js. They provide modern, Promise-based asynchronous handling of DNS queries, making them highly useful for networking and security applications.


1. dnsPromises.resolve6()


Resolves AAAA records (IPv6 addresses) for a hostname.


  • options.ttl: When true, returns TTL values along with addresses.

2. dnsPromises.resolveAny()


Resolves all DNS records for a hostname. The result includes multiple record types such as A, AAAA, MX, NS, TXT, SOA, and more.


3. Other resolve Methods


  • dnsPromises.resolveCaa(): Certification Authority Authorization records.
  • dnsPromises.resolveCname(): Canonical name records.
  • dnsPromises.resolveMx(): Mail exchange records.
  • dnsPromises.resolveNaptr(): Regular expression-based records.
  • dnsPromises.resolveNs(): Name server records.
  • dnsPromises.resolvePtr(): Pointer records.
  • dnsPromises.resolveSoa(): Start of authority records.
  • dnsPromises.resolveSrv(): Service records.
  • dnsPromises.resolveTlsa(): Certificate association records.
  • dnsPromises.resolveTxt(): Text records.

4. dnsPromises.reverse()


Performs reverse DNS lookups, resolving an IPv4 or IPv6 address into hostnames.


5. Managing Result Order


  • dnsPromises.setDefaultResultOrder(order): Sets default order (ipv4first, ipv6first, verbatim).
  • dnsPromises.getDefaultResultOrder(): Retrieves the current default order.

6. Setting DNS Servers


Custom DNS servers can be configured using dnsPromises.setServers():


dnsPromises.setServers([
  '8.8.8.8',
  '[2001:4860:4860::8888]',
  '8.8.8.8:1053',
  '[2001:4860:4860::8888]:1053',
]);

Conclusion


The dns.promises API provides a comprehensive set of Promise-based methods for DNS record management in Node.js. With support for multiple record types, reverse lookups, result ordering, and custom server configuration, it enables developers to build robust and flexible networking applications.


Written & researched by Dr. Shahin Siami

Related Articles

Comprehensive Guide to the Node.js VM Module (node:vm)

The node:vm module allows you to compile and execute JavaScript code inside isolated V8 contexts — essentially creating lightweight sandboxes within your Node.js application. These contexts have their own global scope and can run code independently from the main environment. However, vm is NOT a security sandbox. It is powerful for dynamic code execution, template engines, REPLs, plugin systems, and controlled module execution, but it must never be used to run untrusted code.

Continue

Comprehensive Guide to the V8 Module in Node.js (node:v8)

The node:v8 module exposes low-level APIs that interact directly with the V8 JavaScript engine embedded in Node.js. . These APIs provide access to heap statistics, heap snapshots, coverage tools, serialization mechanisms, V8 flags, object queries, and promise lifecycle hooks. The module is essential for performance analysis, memory debugging, tooling, and advanced Node.js internals work.

Continue

Comprehensive Guide to Node.js Worker Threads (node:worker_threads)

The node:worker_threads module enables true multithreading in Node.js by running JavaScript in separate threads. While Node.js is traditionally single‑threaded, worker threads allow CPU‑intensive tasks to run in parallel without blocking the event loop. They support shared memory, zero‑copy transfers, worker pools, resource limits, and advanced synchronization APIs. Worker threads are ideal for heavy computation, data processing, and parallel workloads—while async I/O remains best handled by the main thread.

Continue

Comprehensive Guide to the Node.js util Module (node:util)

The node:util module provides a powerful collection of helper functions used throughout Node.js core and extremely useful for application developers. These utilities support debugging, inspection, formatting, type checking, callback/Promise conversions, argument parsing, text encoding, MIME handling, and more. It is one of the most versatile and essential toolkits in the Node.js ecosystem.

Continue

Comprehensive Guide to the URL Module in Node.js

The node:url module provides tools for parsing, constructing, and manipulating URLs. Node.js supports two URL APIs: WHATWG URL API — modern, browser‑compatible, standards‑based. Legacy Node.js URL API — older, Node‑specific, now discouraged. The WHATWG API is the recommended approach for all modern applications. It provides a clean, consistent interface for working with URL components, query parameters, and structured URL patterns.

Continue

راهنمای جامع UDP / Datagram Sockets در Node.js

ماژول node:dgram پیاده‌سازی کامل سوکت‌های UDP را در Node.js فراهم می‌کند. UDP یک پروتکل سبک، بدون اتصال (connectionless) و مناسب برای برنامه‌های بلادرنگ مانند VoIP، بازی‌ها، IoT، سیستم‌های پخش (broadcast) و چندپخشی (multicast) است. این ماژول امکان ساخت سوکت، ارسال و دریافت دیتاگرام، مدیریت TTL، عضویت در گروه‌های multicast، کنترل بافرها، و مدیریت رفتار سطح پایین شبکه را فراهم می‌کند.

Continue