node:dns module enables name resolution for looking up IP addresses of host names.
Import
DNS Resolution Methods
There are two types of DNS resolution in Node.js:dns.lookup()- Uses the operating system’s facilities (e.g.,/etc/hosts)dns.resolve*()- Connects directly to DNS servers
dns.lookup()
Basic Usage
With Options
Get All Addresses
Parameters
hostnameoptionsfamily4, 6, or 0 (both)hintsgetaddrinfoflagsallReturn all addressesorder'ipv4first','ipv6first', or'verbatim'
callbackerraddressfamily
DNS Resolve Methods
dns.resolve4()
Resolve IPv4 addresses (A records).With TTL Information
dns.resolve6()
Resolve IPv6 addresses (AAAA records).dns.resolveMx()
Resolve mail exchange records.dns.resolveTxt()
Resolve text records.dns.resolveCname()
Resolve canonical name records.dns.resolveNs()
Resolve name server records.dns.resolveSrv()
Resolve service records.dns.resolveSoa()
Resolve start of authority record.dns.resolvePtr()
Resolve pointer records (reverse DNS).dns.resolveCaa()
Resolve certification authority authorization records.Reverse DNS Lookup
DNS Server Configuration
Get DNS Servers
Set DNS Servers
Class: dns.Resolver
Create independent DNS resolvers with custom settings.Creating a Resolver
Resolver Options
Resolver Methods
resolver.setLocalAddress([ipv4][, ipv6])
Set the IP addresses to use when making DNS requests.resolver.cancel()
Cancel all outstanding DNS queries.DNS Promises API
Using Promises
Lookup with Promises
Resolver with Promises
Error Handling
Common Error Codes
ENOTFOUND- Domain name not foundENODATA- No data returned from DNSETIMEOUT- DNS query timed outECONNREFUSED- Connection refusedECANCELLED- Query was cancelled
Error Handling Example
Setting Default Result Order
Example: Complete DNS Tool
Example: DNS Caching
Performance Considerations
- Use
dns.lookup()for simple hostname resolution - It’s faster and uses the OS cache - Use
dns.resolve*()for DNS-specific queries - Direct DNS server communication - Implement DNS caching - Reduce DNS queries for frequently accessed domains
- Handle errors gracefully - DNS failures are common
- Use Promise API - Cleaner async/await syntax