Node.JS DNS Module

We have so far looked at many node.js modules such as express module, web module, path module etc. In this article we are going to study yet another module i.e node.js DNS module which provide underlying system’s name resolution and DNS look up facilities. DNS module consists of an asynchronous network wrapper. DNS module can be imported via “var DNS = require(“dns”)” command. Let’s have a look at some of the most commonly used DNS functions.

dns.lookup(adress, options, callback)

The dns lookup method takes any website address as its first parameter and returns the corresponding first IPV4 or IPV6 record. The options parameter can be an integer or object. If no options are provided both IPV4 and IPV6 are valid inputs. The third parameter is the callback functions.

dns.lookupservice(address, port, callback)

This function converts the address and port passed to it as parameters into host name and service name running at the port. It uses getnameinfo method to perform transformations.

dns.resolve(address, rrbytes, callback)

This function converts any physical address such as “www.knowledgehills.com” to array of record types. The record types are specified by the second parameter “rrbyte”. Finally the third method is the callback function.

dns.getServers()

This method returns list of all the servers that are currently being used to resolve client requests.

dns.setServers()

This method is reverse of the getServers method and is used to register all the IP addresses passed to it as resolution servers.

Take a look at the following example to understand node.js dns module lookup method.

var DNS = require('dns');

DNS.lookup('www.knowledgehills.com', function onLookup(err, address, family) {
   console.log('address:', address);
   DNS.reverse(address, function (err, hostnames) {
      if (err) {
         console.log(err.stack);
      }

      console.log('The reverse of  ' + address + ': ' + JSON.stringify(hostnames));
   });  
});

Download the code Try the code

Take a look at the above code, here we first import the required dns module via require(‘dns’) module. Next we used the dns.lookup() function and passed it “www.knowledgehills.com”. The callback function converts this hostname into IP addresses. Next we printed the reverse of the IP into domain name.

Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .