dns module example in Node.js
The dns
module in Node.js provides an interface to perform DNS (Domain Name System) resolutions and related operations. DNS is crucial for translating domain names (like example.com
) into IP addresses (like 192.0.2.1
) and vice versa, enabling network communication over the Internet. Here’s an overview of what the dns
module offers and how to use it:
Key Functions and Methods in the dns
Module
-
dns.lookup(hostname[, options], callback)
- Performs a DNS lookup on the given
hostname
. options
can include properties likefamily
(4 for IPv4, 6 for IPv6),hints
, etc.callback
is a function with parameters(err, address, family)
whereaddress
is the resolved IP address andfamily
is the address family (4 for IPv4, 6 for IPv6).
const dns = require('dns'); dns.lookup('www.example.com', (err, address, family) => { if (err) { console.error('DNS lookup error:', err); return; } console.log('IP address:', address); console.log('IP version:', family); // Typically 4 (IPv4) or 6 (IPv6) });
- Performs a DNS lookup on the given
-
dns.resolve(hostname[, rrtype], callback)
- Resolves all records (
A
,AAAA
,MX
,TXT
, etc.) for the givenhostname
. rrtype
(optional) specifies the record type to query (default isA
for IPv4 addresses).
dns.resolve('www.example.com', 'A', (err, records) => { if (err) { console.error('DNS resolve error:', err); return; } console.log('Records:', records); });
- Resolves all records (
-
dns.reverse(ip, callback)
- Performs a reverse DNS lookup, translating an IP address back into one or more domain names (hostnames).
dns.reverse('8.8.8.8', (err, hostnames) => { if (err) { console.error('Reverse DNS lookup error:', err); return; } console.log('Hostnames:', hostnames); });
Additional Methods
dns.resolve4(hostname, callback)
: Resolves IPv4 addresses (A
records) for the givenhostname
.dns.resolve6(hostname, callback)
: Resolves IPv6 addresses (AAAA
records) for the givenhostname
.dns.resolveMx(hostname, callback)
: Resolves mail exchange records (MX
records) for the givenhostname
.dns.resolveTxt(hostname, callback)
: Resolves text records (TXT
records) for the givenhostname
.dns.resolveSrv(hostname, callback)
: Resolves service records (SRV
records) for the givenhostname
.
Promises and async/await
Starting from Node.js version 15.0.0, the dns
module supports promises and can be used with async/await
for cleaner asynchronous code:
const dns = require('dns').promises;
async function resolveDomain() {
try {
const addresses = await dns.resolve4('www.example.com');
console.log('IP addresses:', addresses);
} catch (err) {
console.error('DNS resolution error:', err);
}
}
resolveDomain();
Published on: Jun 19, 2024, 03:11 AM