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. optionscan include properties likefamily(4 for IPv4, 6 for IPv6),hints, etc.callbackis a function with parameters(err, address, family)whereaddressis the resolved IP address andfamilyis 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 isAfor 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 (Arecords) for the givenhostname.dns.resolve6(hostname, callback): Resolves IPv6 addresses (AAAArecords) for the givenhostname.dns.resolveMx(hostname, callback): Resolves mail exchange records (MXrecords) for the givenhostname.dns.resolveTxt(hostname, callback): Resolves text records (TXTrecords) for the givenhostname.dns.resolveSrv(hostname, callback): Resolves service records (SRVrecords) 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