Node.js dns Module
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:
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
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
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
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
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
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
console.log('Asynchronous result:', address);
});
Promise version
Starting from Node.js v10.6.0,dnsthe module's methods also provide Promise-based versions:
Example
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
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 existESERVFAIL: DNS server returned failureETIMEOUT: DNS query timed out
Practical application examples
Check whether a domain can be resolved
Example
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
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:
- Cache results: For frequently queried domains, consider caching results at the application layer
- Concurrency limits: Avoid making a large number of DNS queries at the same time
- Timeout settings: Set a reasonable timeout for DNS queries
Example
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 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
// 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
// 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
// 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
// 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 as
dns.lookup()、dns.resolve()etc., non-blocking, suitable for concurrent tasks. - Synchronous methods: such as
dns.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.
Node.js built-in modules