web-development top banner

What Is the Use of DNS Module in Node.Js?

Read it in 8 Mins

Last updated on
22nd Jun, 2022
Published
16th Mar, 2021
Views
9,664
What Is the Use of DNS Module in Node.Js?

Node.js gives the provision of using different modules. In this article, we will look into the use of DNS module in Node.  

What is DNS and its importance?

DNS stands for Domain Name System. The main function of the DNS is to translate the IP Address, which is a numerical label assigned to your computer. IP addresses can be thought of as names of computers on a network and are used to distinguish different devices and their locations For example, 8.8.8.8 is one of the many public IP addresses of Google.com. 

So, DNS can be considered as phonebook of the Internet. When we type any address like www.example.com in our browser, that request is sent to the Name Server which converts it to an IP Address(like 12.34.56.78). This is then sent to the respective server for further processing. The figure below shows how exactly this happens. 

What is DNS and its importance

Syntax 

The syntax for including the DNS module in our node application is – 

const dns = require(‘dns’) 

DNS methods and its descriptions

We will look into a real example and some important DNS methodsLet us setup a basic node application by giving the command npm init -y in terminal, inside a folder. I had created an empty NodeJS folder for the same. 

$ npm init -y 
Wrote to D:\NodeJS\package.json: 
{ 
  "name": "NodeJS", 
  "version": "1.0.0", 
  "description": "", 
  "main": "index.js", 
  "scripts": { 
    "test": "echo \"Error: no test specified\" && exit 1" 
  }, 
  "keywords": [], 
  "author": "", 
  "license": "ISC" 
}

The above commands create a basic package.json file, which is the basis of any Node.js project. We are using the -y option, so that we don’t have to enter the details manually. 

Next, open the folder in a code editor which is VSCode in my case. Here, I have created a file dns.js and the first line contains the code for importing the dns module.

1. lookup()

Next, we will call the dns lookup function, which takes two arguments. The first is the domain we want to lookup, which can be anything and is knowledgehut.com in our case. The second is the callback or function that we want to run, once the lookup is complete. 

The function that runs on completion takes two arguments. The first argument contains an error, if one occurs, and the second is the value or the IP address of the domain. 

So, inside our function if we have an error we are printing it in the console and returning, which means no further code will run. If we don’t have an error, we are printing the value. 

Add the below code in a dns.js file.

const dns = require('dns'); 
dns.lookup('knowledgehut.com', (err, value) => { 
    if(err) { 
        console.log(err); 
        return; 
    } 
    console.log(value); 
}) 

To run this, I am opening the Integrated terminal, which comes in VSCode by pressing Ctrl+J on Windows or Cmd+J on Mac. Here, give the command node dns to run our file dns.js. The output of the same is below. 

54.147.15.161

When we run this program, we are not getting any error and getting the IP address of the domain name.

2. resolve() 

The function resolve() is pretty much identical to the lookup() function. Our code remains the same and we have only changed the lookup to resolve. Add the below code in a dns.js file.

const dns = require('dns'); 
dns.resolve('knowledgehut.com', (err, value) => { 
    if(err) { 
        console.log(err); 
        return; 
    } 
    console.log(value); 
}) 

We can get the output by running node dns command from terminal.

[ '34.236.195.104', 
  '50.16.1.247',     
  '54.147.15.161',   
  '3.223.64.88' ]

But as we can see from the output, we got all the IP addresses associated with this domain.

The resolve function actually goes and makes a network request to the DNS system, to see how many IP addresses are registered with that domain name. The lookup function actually just uses the computer’s internal mechanism first to see if there is an IP address that it can return without having to do a network request. 

So, resolve function is more accurate and should be used in production as it gives all the IP addresses associated with the domain. 

You can also provide another argument to the resolve function to specify what type of record you want to look up. For example, with the DNS system you can find the Mail exchange record of the domain. This record handles the request, when you send an email to the domain, and specifies which server should handle the request.

So, in our code we will add MX as the second argument. Add the below code in a dns.js file.

const dns = require('dns'); 
dns.resolve('knowledgehut.com', 'MX', (err, value) => { 
    if(err) { 
        console.log(err); 
        return; 
    } 
    console.log(value); 
})

On running the node dns command from the Integrated Terminal again, we are getting the information of the Mail exchange of that domain in an array.

{ exchange: 'mail.knowledgehut.com', priority: 0 } ]  

3. reverse() 

Now, we will look into the reverse function. It works exactly the same as lookup() and resolve(), but instead of supplying a domain name, we are supplying an IP address. This function goes into the DNS system, to find out if there are any reverse records associated with this IP address. We are using 8.8.8.8, which is the publicly available IP address for Google. Add the below code in a dns.js file. 

const dns = require('dns'); 
dns.reverse('8.8.8.8', (err, value) => { 
    if(err) { 
        console.log(err); 
        return; 
    } 
    console.log(value); 
}) 

On running the node dns again, we will get the reverse record within an array. 

[ 'dns.google' ]  

4. lookUp Service() 

This can be used to get the information of host, which includes the hostname and the service. We need to provide a valid IP address and a valid Port as arguments. It uses the Operating Systems getnameinfo to get this data. 

If the IP address or the Port are not valid, a TypeError will be thrown.   

In our example, we are providing a known IP address along with the port 587. This port is used for Mail Exchange(MX).  Then we are console logging the host and serviceAdd the below code in a dns.js file. 

const dns = require('dns'); 
dns.lookupService('34.236.195.104', 587, (err, host, service) => { 
    if(err) { 
        console.log(err); 
        return; 
    } 
    console.log(host,'\n', service); 
})

It is shown in console on running node dns in Integrated Terminal.

ec2-34-236-195-104.compute-1.amazonaws.com   
 587

5. resolve4()

The resolve4 method is almost similar to the resolve() method. It also returns an array of IP addresses, but only the IPv4 addresses and not the newer IPv6 addresses. Still most of the websites use IPv4 address and this function will give a valid output. Add the below code in a dns.js file.

const dns = require('dns'); 
dns.resolve4('knowledgehut.com', (err, value) => { 
    if(err) { 
        console.log(err); 
        return; 
    } 
    console.log(value); 
}) 

It is shown in console on running node dns in Integrated Terminal. 

[ '50.16.1.247',    
  '54.147.15.161',  
  '34.236.195.104', 
  '3.223.64.88' ] 

6. resolve6()

The IPv4 is a 32 bit address, developed in the 90s. But since there are only 4 billion addresses, the world ran out and they were all used up. So, IPv6 was invented and since then many websites have this new IPv6 address. The resolve6() method internal mechanism is also like the resolve() method, but it only returns array of IPv6 addresses. Add the below code in a dns.js file.

const dns = require('dns'); 
dns.resolve6('nodejs.org', (err, value) => { 
    if(err) { 
        console.log(err); 
        return; 
    } 
    console.log(value); 
}) 

It is shown in console on running node dns in Integrated Terminal.

[ '2606:4700:8d75:a0e6:9d7:10c:f52a:f808' ]

7. resolveMx()

The resolveMx() method is used to get the Mail exchange records for a hostname. The Mail exchange records are also known as MX records. We need to pass the hostname as argument and we will receive the details in an array, if the request was successful. Add the below code in a dns.js file.

const dns = require('dns'); 
dns.resolveMx('nodejs.org', (err, value) => { 
    if(err) { 
        console.log(err); 
        return; 
    } 
    console.log(value); 
})

It is shown in console on running node dns in Integrated Terminal.  

{ exchange: 'aspmx.l.google.com', priority: 10 },      
  { exchange: 'alt1.aspmx.l.google.com', priority: 20 }, 
  { exchange: 'alt2.aspmx.l.google.com', priority: 20 }, 
  { exchange: 'aspmx2.googlemail.com', priority: 30 },   
  { exchange: 'aspmx3.googlemail.com', priority: 30 } ] 

8. resolveNs() 

The resolveNs() method is used to get the Name Server(NS records) information of a hostname. The hostname is passed as argument and we receive the information back in an array. Add the below code in a dns.js file. 

const dns = require('dns%
Profile

KnowledgeHut

Author
KnowledgeHut is an outcome-focused global ed-tech company. We help organizations and professionals unlock excellence through skills development. We offer training solutions under the people and process, data science, full-stack development, cybersecurity, future technologies and digital transformation verticals.