Home  Nodejs   Dns module ...

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

  1. dns.lookup(hostname[, options], callback)

    • Performs a DNS lookup on the given hostname.
    • options can include properties like family (4 for IPv4, 6 for IPv6), hints, etc.
    • callback is a function with parameters (err, address, family) where address is the resolved IP address and family 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)
    });
    
  2. dns.resolve(hostname[, rrtype], callback)

    • Resolves all records (A, AAAA, MX, TXT, etc.) for the given hostname.
    • rrtype (optional) specifies the record type to query (default is A for IPv4 addresses).
    dns.resolve('www.example.com', 'A', (err, records) => {
      if (err) {
        console.error('DNS resolve error:', err);
        return;
      }
      console.log('Records:', records);
    });
    
  3. 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

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  
 

Comments

Add your comment