The DNS (Domain Name System) module provides a way of performing name resolutions. It translates human-readable domain names (like google.com) into computer-readable IP addresses (like 142.250.190.46).
This is highly useful when you need to verify domain names or interact with raw networking data on a low level.
The most common function is dns.lookup(), which uses the operating system's underlying facilities to resolve a domain name into its IP address.
const dns = require('dns');
// Look up the IP address for google.com
dns.lookup('google.com', (err, address, family) => {
if (err) throw err;
console.log(IP Address: ${address});
console.log(IP Version: IPv${family});
});
If you want to bypass the operating system and directly query the DNS servers for specific types of records (such as MX records for email servers), use dns.resolve().
const dns = require('dns');
// Find mail exchange servers for gmail.com
dns.resolve('gmail.com', 'MX', (err, addresses) => {
if (err) throw err;
console.log('Mail Servers for Gmail:');
console.log(addresses);
});
What is the primary purpose of the DNS module?