A dns
module in Node.js.
The dns
module is named for the
To verify a URL, we can use the lookup()
method of the dns
module.
dns.lookup([hostname], (error, address, family){// CODE BODY})
hostname
: The name of the website on the internet, e.g., google.com, [educative.io[(http://educative.io), etc.
A callback function that contains the following:
error
: The error that is returned when the hostname is not valid.
address
: The
family
: This is the
dns.lookup()
can use the callback function to return an error
or the address and hostname
.
A callback function is a function passed into another function that must execute when the other function has finished executing.
Let’s verify the hostname educative.io.
In the code below, we import the dns
module. The dns
module uses the lookup()
method to verify the hostname passed to it, i.e., educative.io. If an error occurs, which is normally an incorrect hostname, an error is logged to the console; otherwise, the IP address and IP version are logged to the console.
// import dns moduleconst dns = require("dns");// lookup the hostname passed as argumentdns.lookup("educative.io", (error, address, family) => {// if an error occurs, eg. the hostname is incorrect!if (error) {console.error(error);} else {// if no error existsconsole.log(`The ip address is ${address} and the ip version is ${family}`);}});
An illustration of the code demo is shown below.
When the hostname, educative.io, is looked up by the dns
module, the first thing to get is the IP address. If the IP address is not found, then an error will occur.
In the code above, we verify and resolve the hostname educative.io.
Note: The hostname can also start with “www”, e.g., www.educative.io.
Let’s verify a hostname that is incorrect. Let’s use educattiivvee.io
.
// import dns moduleconst dns = require("dns");// lookup the hostname passed as argumentdns.lookup("educattiivve.io", (error, address, family) => {// if an error occurs, eg. the hostname is incorrect!if (error) {console.error(error.message);} else {// if no error existsconsole.log(`The ip address is ${address} and the ip version is ${family}`);}});