How to use the dns module to verify a URL in Node.js
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.
Syntax
dns.lookup([hostname], (error, address, family){// CODE BODY})
Parameters
-
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 address of the hostname.IP internet protocol -
family: This is the version number, which is 4 or 6, i.e., IP version 4 and 6.IP internet protocol
-
Return value
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.
Demo
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.
How to verify an incorrect hostname
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}`);}});