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. Syntax The syntax for including the DNS module in our node application is – const dns = require(‘dns’) DNS methods and its descriptionsWe will look into a real example and some important DNS methods. Let 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.161When 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 service. Add 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 5875. 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'); dns.resolveNs('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. [ 'pablo.ns.cloudflare.com', 'meera.ns.cloudflare.com' ] 9. resolveSoa() The resolveSoa() method is used to get the Start of Authority record(SOA record) for a given hostname. The SOA records contain a lot of important information about the hostname like Name Server, Host Master, Expiry time. The hostname is passed as argument, and we receive all the information in an object. Add the below code in a dns.js file. const dns = require('dns'); dns.resolveSoa('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. { nsname: 'meera.ns.cloudflare.com', hostmaster: 'dns.cloudflare.com', serial: 2035938779, refresh: 10000, retry: 2400, expire: 604800, minttl: 3600 } 10. resolveTxt() The resolveTxt() method is used to get the txt queries(TXT records) for a given hostname. The TXT records were actually intended to put human-readable notes in DNS, by the domain administrator. But nowadays, it is also used to prevent email spam. In the resolveTxt() method the hostname is passed as argument, but we receive the output as a two-dimensional array of text records available for that hostname. Add the below code in a dns.js file.const dns = require('dns'); dns.resolveTxt('nodejs.org', (err, value) => { if(err) { console.log(err); return; } console.log(value); }) The output is shown in console on running node dns in Integrated Terminal. [ [ 'v=spf1 include:aspmx.googlemail.com -all' ] ] 11. resolvePtr() The resolvePtr() method is used to get the pointer records(PTR records) for a given hostname. Now, a PTR record maps an IP address to a domain and is also called “reverse DNS entry”. It is used to convert an IP address to a domain name. This is mainly used as a security and anti-spam measure. 12. resolveNaptr() The resolveNaptr() method is used to get the Naming Authority Pointer records(NAPTR records) for a given hostname. The NAPTR records are newer type of DNS records, in which we can write in regular expressions. The NAPTR records are mostly used in applications, which support Internet Telephony. The resolveNaptr() method is useful to know, whether a domain supports SIP or some other VoIP(Voice Over IP) services. 13. resolveSrv() The resolveSrv() method is used to get the service records(SRV records) for a given hostname. The service records specify the host and port for specific services on a server like voice over IP(VoIP), instant messaging and other services. 14. setServers() The setServers() is a very important method, which is used to set the IP address and port of servers. The argument to this method, is an array of formatted array. Example for the same is below. dns.setServers([ '4.4.4.4', '[2001:4860:4860::8888]', '4.4.4.4:1053', '[2001:4860:4860::8888]:1053' ]); 15. getServers() The getServers() method of DNS is used to get all the IP addresses associated with a server. It returns the IP addresses, belonging to the server in an array. DNS promises API The dns.promises API returns promise objects, instead of the callbacks which we have seen earlier. So, they are more modern as most of the JavaScript community is moving towards promises, instead of callbacks. We need to access the promises API by using require(‘dns’).promises Almost all the methods that are in dns are also available in DNS promises API. The complete list is below. resolver.getServers() resolver.resolve() resolver.resolve4() resolver.resolve6() resolver.resolveAny() resolver.resolveCaa() resolver.resolveCname() resolver.resolveMx() resolver.resolveNaptr() resolver.resolveNs() resolver.resolvePtr() resolver.resolveSoa() resolver.resolveSrv() resolver.resolveTxt() resolver.reverse() resolver.setServers() We will look into some of the examples, along with syntaxes. 16. resolver.resolve4() This method takes the hostname as argument. On success the Promise is resolved with an array of IPv4 addresses. In the below example, we are using a different import, than our previous section. Since, the resolver.resolve4() returns a promise we can use the modern syntax of ‘then and catch’ block. The .then is executed if the Promise resolves to success and the .error is executed if the Promise fails. Add the below code in a dns.js file. const { Resolver } = require('dns').promises; const resolver = new Resolver(); resolver.resolve4('geeksforgeeks.org') .then(addresses => console.log(addresses)) .catch(err => console.log(err)) The output is shown in console on running node dns in Integrated Terminal. In the case of success, we get an array with IPv4 addresses as in our case. [ '34.218.62.116' ] 17. resolver.resolveMx() This method takes the hostname as argument. On success the Promise is resolved with an array of Mail exchange(MX records) records. In the below example, we are using the latest async-await format for the Promise. Add the below code in a dns.js file. const { Resolver } = require('dns').promises; const resolver = new Resolver(); (async function() { const addresses = await resolver.resolveMx('nodejs.org'); console.log(addresses) })() The output is shown in console on running node dns in Integrated Terminal. [ { 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 }, { exchange: 'aspmx.l.google.com', priority: 10 } ]18. resolver.getServers() The resolver.getServers() method returns an array of IP addresses. We can use it as below, where we are first getting the IPv6 address, by using the resolve6() method. Once, we receive it we are using it inside the .then block and it will return all the IP addresses of the server. Add the below code in a dns.js file. const { Resolver } = require('dns').promises; const resolver = new Resolver(); resolver.resolve6('nodejs.org') .then(addresses => { console.log('IPv6 is ', addresses); console.log('Server address is ', resolver.getServers()); }) .catch(err => console.log(err)) The output is shown in the console on running node dns in Integrated Terminal. IPv6 is [ '2606:4700:8d75:a0e6:9ca:10c:f52a:f808' ] Server address is [ '2405:201:3001:a3a::c0a8:1d01', '192.168.29.1' ] Error Codes A lot of errors can be thrown when we use any of the dns or dns promise methods. The errors which we can get are as below. dns.NODATA: DNS server returned answer with no data. dns.FORMERR: DNS server claims query was mis-formatted. dns.SERVFAIL: DNS server returned general failure. dns.NOTFOUND: Domain name was not found. dns.NOTIMP: DNS server does not implement requested operation. dns.REFUSED: DNS server refused the query. dns.BADQUERY: Mis formatted DNS query. dns.BADNAME: Mis formatted host name. dns.BADFAMILY: Unsupported address family. dns.BADRESP: Mis formatted DNS reply. dns.CONNREFUSED: Could not contact DNS servers. dns.TIMEOUT: Timeout happened while contacting DNS servers. dns.EOF: End of file. dns.FILE: Error reading file. dns.NOMEM: Out of memory. dns.DESTRUCTION: Channel is being destroyed. dns.BADSTR: Mis formatted string. dns.BADFLAGS: Illegal flags specified. dns.NONAME: Given host name is not numeric. dns.BADHINTS: Illegal hints flags specified. dns.NOTINITIALIZED: c-ares library initialization not yet performed. dns.LOADIPHLPAPI: Error loading iphlpapi.dll. dns.ADDRGETNETWORKPARAMS: Could not find GetNetworkParams function. dns.CANCELLED: DNS query cancelled.We will see an example of DNS error. In the below example of resolver.resolve6() method, we have given a domain name which doesn’t exist. Add the below code in a dns.js file. const { Resolver } = require('dns').promises; const resolver = new Resolver(); resolver.resolve6('abc.tech') .then(addresses => console.log(addresses)) .catch(err => console.log(err)) So, we are getting the NOTFOUND error, when we are running node dns from terminal. { Error: queryAaaa ENOTFOUND abc.tech at QueryReqWrap.onresolve [as oncomplete] (internal/dns/promises.js:163:17) errno: 'ENOTFOUND', code: 'ENOTFOUND', syscall: 'queryAaaa', hostname: 'abc.tech' } Implementation considerations There is a difference in the was dns.lookup() runs and the other dns methods like dns.resolve(), dns.reverse() runs. The dns.lookup() will always resolve a given name using the same way a ping command works. It doesn’t make a network call and is implemented as a synchronous call to getaddrinfo() function. The functions dns.resolve() and dns.reverse() are implemented quite differently, and they don’t use the getaddrinfo() function. They will always perform a DNS query on the network. So, the result is more accurate and updated. So, these differences can have significant consequences to our NodeJS program and should be considered. SummaryIn this post, we have learnt about the various DNS methods available in our Node.JS. We can use these methods to get a lot of information about any host. Many of these methods need us to have network access to the required, but they can always be used for internal NodeJS codes also. Knowledge of these methods, along with network concepts are important for NodeJS application development. # What Is the Use of DNS Module in Node.Js? 9K 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. 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": "",
}

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');
dns.resolveNs('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.

[ 'pablo.ns.cloudflare.com', 'meera.ns.cloudflare.com' ]

### 9. resolveSoa()

The resolveSoa() method is used to get the Start of Authority record(SOA record) for a given hostname. The SOA records contain a lot of important information about the hostname like Name Server, Host Master, Expiry time. The hostname is passed as argument, and we receive all the information in an object. Add the below code in a dns.js file.

const dns = require('dns');
dns.resolveSoa('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.

{ nsname: 'meera.ns.cloudflare.com',
hostmaster: 'dns.cloudflare.com',
serial: 2035938779,
refresh: 10000,
retry: 2400,
expire: 604800,
minttl: 3600 } 

### 10. resolveTxt()

The resolveTxt() method is used to get the txt queries(TXT records) for a given hostname. The TXT records were actually intended to put human-readable notes in DNS, by the domain administrator. But nowadays, it is also used to prevent email spam.

In the resolveTxt() method the hostname is passed as argument, but we receive the output as a two-dimensional array of text records available for that hostname.

Add the below code in a dns.js file.

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

The output is shown in console on running node dns in Integrated Terminal.

[ [ 'v=spf1 include:aspmx.googlemail.com -all' ] ]

### 11. resolvePtr()

The resolvePtr() method is used to get the pointer records(PTR records) for a given hostname. Now, a PTR record maps an IP address to a domain and is also called “reverse DNS entry”. It is used to convert an IP address to a domain name. This is mainly used as a security and anti-spam measure.

### 12. resolveNaptr()

The resolveNaptr() method is used to get the Naming Authority Pointer records(NAPTR records) for a given hostname. The NAPTR records are newer type of DNS records, in which we can write in regular expressions. The NAPTR records are mostly used in applications, which support Internet Telephony. The resolveNaptr() method is useful to know, whether a domain supports SIP or some other VoIP(Voice Over IP) services.

### 13. resolveSrv()

The resolveSrv() method is used to get the service records(SRV records) for a given hostname. The service records specify the host and port for specific services on a server like voice over IP(VoIP), instant messaging and other services.

### 14. setServers()

The setServers() is a very important method, which is used to set the IP address and port of servers. The argument to this method, is an array of formatted array. Example for the same is below.

dns.setServers([
'4.4.4.4',
'[2001:4860:4860::8888]',
'4.4.4.4:1053',
'[2001:4860:4860::8888]:1053'
]); 

### 15. getServers()

The getServers() method of DNS is used to get all the IP addresses associated with a server. It returns the IP addresses, belonging to the server in an array.

DNS promises API

The dns.promises API returns promise objects, instead of the callbacks which we have seen earlier. So, they are more modern as most of the JavaScript community is moving towards promises, instead of callbacks. We need to access the promises API by using require(‘dns).promises

Almost all the methods that are in dns are also available in DNS promises API. The complete list is below.

• resolver.getServers()
• resolver.resolve()
• resolver.resolve4()
• resolver.resolve6()
• resolver.resolveAny()
• resolver.resolveCaa()
• resolver.resolveCname()
• resolver.resolveMx()
• resolver.resolveNaptr()
• resolver.resolveNs()
• resolver.resolvePtr()
• resolver.resolveSoa()
• resolver.resolveSrv()
• resolver.resolveTxt()
• resolver.reverse()
• resolver.setServers()

We will look into some of the examples, along with syntaxes.

### 16. resolver.resolve4()

This method takes the hostname as argument. On success the Promise is resolved with an array of IPv4 addresses. In the below example, we are using a different import, than our previous section.

Since, the resolver.resolve4() returns a promise we can use the modern syntax of then and catch block. The .then is executed if the Promise resolves to success and the .error is executed if the Promise fails. Add the below code in a dns.js file.

const { Resolver } = require('dns').promises;
const resolver = new Resolver();
resolver.resolve4('geeksforgeeks.org')
.catch(err => console.log(err)) 

The output is shown in console on running node dns in Integrated Terminal.

In the case of success, we get an array with IPv4 addresses as in our case.

[ '34.218.62.116' ]

### 17. resolver.resolveMx()

This method takes the hostname as argument. On success the Promise is resolved with an array of Mail exchange(MX records) records.  In the below example, we are using the latest async-await format for the Promise. Add the below code in a dns.js file.

const { Resolver } = require('dns').promises;
const resolver = new Resolver();
(async function() {
const addresses = await resolver.resolveMx('nodejs.org');
})() 

The output is shown in console on running node dns in Integrated Terminal.

[ { 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 },
{ exchange: 'aspmx.l.google.com', priority: 10 } ]

### 18. resolver.getServers()

The resolver.getServers() method returns an array of IP addresses. We can use it as below, where we are first getting the IPv6 address, by using the resolve6() method. Once, we receive it we are using it inside the .then block and it will return all the IP addresses of the server.

Add the below code in a dns.js file.

const { Resolver } = require('dns').promises;
const resolver = new Resolver();
resolver.resolve6('nodejs.org')
console.log('IPv6 is ', addresses);
console.log('Server address is ', resolver.getServers());
})
.catch(err => console.log(err)) 

The output is shown in the console on running node dns in Integrated Terminal.

IPv6 is  [ '2606:4700:8d75:a0e6:9ca:10c:f52a:f808' ]
Server address is  [ '2405:201:3001:a3a::c0a8:1d01', '192.168.29.1' ] 

Error Codes

A lot of errors can be thrown when we use any of the dns or dns promise methods. The errors which we can get are as below.

• dns.NODATA: DNS server returned answer with no data.
• dns.FORMERR: DNS server claims query was mis-formatted.
• dns.SERVFAIL: DNS server returned general failure.
• dns.NOTFOUND: Domain name was not found.
• dns.NOTIMP: DNS server does not implement requested operation.
• dns.REFUSED: DNS server refused the query.
• dns.BADQUERYMis formatted DNS query.
• dns.BADNAMEMis formatted host name.
• dns.CONNREFUSED: Could not contact DNS servers.
• dns.TIMEOUT: Timeout happened while contacting DNS servers.
• dns.EOF: End of file.
• dns.FILE: Error reading file.
• dns.NOMEM: Out of memory.
• dns.DESTRUCTION: Channel is being destroyed.
• dns.BADSTRMis formatted string.
• dns.BADFLAGS: Illegal flags specified.
• dns.NONAME: Given host name is not numeric.
• dns.BADHINTS: Illegal hints flags specified.
• dns.NOTINITIALIZED: c-ares library initialization not yet performed.
• dns.ADDRGETNETWORKPARAMS: Could not find GetNetworkParams function.
• dns.CANCELLED: DNS query cancelled.

We will see an example of DNS error. In the below example of resolver.resolve6() method, we have given a domain name which doesn’t exist. Add the below code in a dns.js file.

const { Resolver } = require('dns').promises;
const resolver = new Resolver();
resolver.resolve6('abc.tech')
.catch(err => console.log(err)) 

So, we are getting the NOTFOUND error, when we are running node dns from terminal.

{ Error: queryAaaa ENOTFOUND abc.tech
at QueryReqWrap.onresolve [as oncomplete] (internal/dns/promises.js:163:17)
errno: 'ENOTFOUND',
code: 'ENOTFOUND',
syscall: 'queryAaaa',
hostname: 'abc.tech' } 

### Implementation considerations

There is a difference in the was dns.lookup() runs and the other dns methods like dns.resolve(), dns.reverse() runs.

The dns.lookup() will always resolve a given name using the same way a ping command works. It doesn’t make a network call and is implemented as a synchronous call to getaddrinfo() function.

The functions dns.resolve() and dns.reverse() are implemented quite differently, and they don’t use the getaddrinfo() function. They will always perform a DNS query on the network. So, the result is more accurate and updated.

So, these differences can have significant consequences to our NodeJS program and should be considered.

Summary

In this post, we have learnt about the various DNS methods available in our Node.JS. We can use these methods to get a lot of information about any host. Many of these methods need us to have network access to the required, but they can always be used for internal NodeJS codes also.

Knowledge of these methods, along with network concepts are important for NodeJS application development.

### Nabendu Biswas

Author

Nabendu Biswas is a Full Stack JavaScript Developer, who has been working in the IT industry for the past 16 years and has worked for world’s top development firms, and Investment banks. He is a passionate tech blogger. He is also a tech youtuber and loves to teach people JavaScript. He is also an Apress author with three Gatsby books published.

## Back Up, Restore, and Migrate a MongoDB Database

Popular among both enterprises and startups, MongoDB is a database that is perfectly suited for web-apps that need to scale once the user base increases. MongoDB is different from traditional relational databases because it uses json like objects to store data, instead of tables in relational databases. In this post, we will learn to backup and restore a MongoDB database. In all software products there is an import and export feature, which in database terms, deals with human-readable format. On the other hand, the backup and restore operations use MongoDB specific data, which preserve the MongoDB attributes.  So, when migrating the database, we should prefer backup and restore over import and export. But we should also keep in mind that our source and target systems are compatible, which means that both should be Windows or both should be a Linux based system like Ubuntu/Mac. Prerequisites We are using Windows 10 in this tutorial. Please make sure you have downloaded the MongoDB Community Server and installed in it. It is a very easy setup and you will find lot of good articles on the internet detailing this out. Please ensure that you have added it in the Environment variable in your PC. Backup Considerations In a production environment, backups act as a snapshot of the database at a certain point. Large and complex databases do fail or can be hacked. If that happens, we can use the last backup file to restore the database to the point, before it failed. These are some of the factors which should be taken into consideration when doing a recovery.  1. Recovery Point Objective We should know the objective of the recovery point, which means how much data we are willing to lose during a backup and restoration. A continuous backup is preferred for critical data like bank information and backups should be taken several times during the day. On the other hand, if the data doesn’t change frequently, then the backup can be taken every 6 months.  2. Recovery Time ObjectiveThis tells how quickly the restoration can be done. During restoration the application will be down for some time; and this downtime should be minimized, or else customer relationships will be lost.  3. Database and Snapshot IsolationThis refers to the distance between the primary database server and the backup server. If they are close enough i.e., in the same building, then the recovery time reduces. However, in the event of a physical event such as a fire, there is a likelihood of it been destroyed with the primary database.   4. Restoration Process We should always test our backups in test servers to see if they will work, in case a restoration is required.  5. Available Storage Backup of database generally takes a lot of space and in most cases, it will never be required. So, we should try to minimize the space taken on the disk, by archiving the database into a zip file.  6. Complexity of DeploymentThe backup strategy should be easy to set and should be automated, so that we don’t have to remember to take the backup after regular intervals. Understanding the Basics The first thing that we should know is that MongoDB uses json and bson(binary json) formats for storing data. So, people coming from a JavaScript background can relate to objects for json, which have a key-value pair. Also, json is the preferred format in which we receive or send data to an API endpoint. You can check the json data of a MongoDB database in any tool or online editors. Even the famous Windows application Notepad++ has a json viewer. An example of a json document looks like below. As we can see from the above example, json is very convenient to work with, especially for developers.  But it doesn’t support all the data types available in bson. So, for backup and restoring, we should use binary bson. The second thing to keep in mind is that MongoDB automatically creates databases and collection names if they don’t exist during restore operations. Third, since MongoDB is a document-based database, in many user cases we store large amounts of data in one collection, such as the whole post of an article. MongoDB is also used extensively in large databases and big data. So, reading and inserting the data can consume a lot of CPU, memory and disk space. We should always run the backups during the non-peak hours like night. As already mentioned earlier, we can use import and export functions for backup and restoration of MongoDB databases, but we should use commands like mongodump and mongorestore to backup and restore respectively. MongoDB backup We will first cover backing up the MongoDB database. For this we use the mongodump command.  First open the Windows command prompt and go to the location in which MongoDB is installed. If you have chosen the default setting, while installing MongoDB though the pop-up it will be installed in a location like C:\Program Files\MongoDB\Server\4.4\bin The version number only will change if you are reading this blog in the future. Also, note that it’s better to run the command prompt in the Admin mode. So, once we open the command prompt, we need to change the directory to MongoDB bin folder by giving the below command. cd C:\Program Files\MongoDB\Server\4.4\binNow, enter mongod and press enter. It will show some json text.Now, we can backup to any location. For this post I am backing up on my Desktop in a Backup folder, which I have created through the command line.Now, we have to run mongodump command, but it should be also present in our MongoDB bin folder. If it is not present, we need to download it from and install it. After this, copy the entire exe files from the download to the MongoDB bin folder. MongoDB Backup with no option Now, run the mongodump command from the bin directory. Here, we are not giving any argument so the backup of the whole database will be taken in the same bin directory.MongoDB Backup to an output directory Now, run the mongodump command from the bin directory. Here, the argument –out specifies the directory in which the data backup will be maintained. In our case we are giving the Backup folder in the  Desktop, which we have created earlier. mongodump --out C:\Users\pc\Desktop\Backup Now, go to the desktop and you can find the backup that has been created in our Backup folder.  MongoDB Backup a specific database Now, we can also backup only a database in mongodump using the –db option. I have an example database, so to backup only that I will use the below command. mongodump --db example --out C:\Users\pc\Desktop\Backup As, you can see in the below output only the example database was backed up. MongoDB Backup a specific collection Now, if we want to only backup a specific collection, we need to use the –collection option and give the collection name. Also, note that the database name is mandatory in this case, as mongodb needs to know about the database to search for the collection. I have a products collection within the example database, so to backup only that I will use the below command. mongodump --db example --out C:\Users\pc\Desktop\Backup –collection products As, you can see in the below output only the products collection from example database was backed up. MongoDB Backup from remote MongoDB instances We can get the backup from remote mongodb instances also. I have a lot of MongoDB databases for my personal projects on MongoDB atlas, which is the free to use Cloud database for MongoDB. To get a backup of remote databases, we have to use the connection string with –uri parameter. I used the below command. mongodump --uri "mongodb+srv://xxxx:xxxxxxxxxxx@cluster0.suvl2.mongodb.net/xxxxxDB?retryWrites=true&w=majority" --out C:\Users\pc\Desktop\Backup You can see in the below output the backup of the remote instance. MongoDB Backup procedures We should try to make the backup procedure as automated as possible. One of the best ways is to use a cron job, so that it can run every day. As, discussed earlier it is best to run the backup in the night when the database has the least load.  Setting up a cron job is easier on a Linux or a Mac because the Windows equivalent of it is not good. Alternatively, you can do install mongodb in WSL2 for Windows which supports Ubuntu.  Suppose, on a Linux host which has a mongoDB instance running, you want to run the backup at 04:04 am daily. For this in the terminal, open the cron editor by running the below command in the terminal. sudo crontab –e Now, in the cron editor, you need to add a command like below for our case. 4 4 * * * mongodump --out /var/backups/mongobackups/date +"%m-%d-%y"Restoring and migrating a MongoDB database When we restore the MongoDB database from a backup, we will be able to take the exact copy of the MongoDB information, including the indexes. We restore MongoDB by using the command mongorestore, which works only with the binary backup produced by mongodump. Now, we have taken the backup of example database earlier and it is in our Backup folder. We will use the below command to restore it. In the arguments we will specify the name of the database first with –db option. After that with –drop, we make sure that the example database is first dropped. And in the final argument, we specify the path of our backup. mongorestore --db example --drop C:\Users\pc\Desktop\Backup\example Now, if we check in terminal, we have our example database restored properly. Conclusion In this article, we have learned about MongoDB backup and restore. We have learned the different options for the backups, and why and when backups are required. Keep learning!
5638
Back Up, Restore, and Migrate a MongoDB Database

Popular among both enterprises and startups, Mong... Read More

## How to Work With Forms In JavaScript

Forms also referred as web forms are a very important part of front end web application development for sake of interaction with users. Most commonly, forms are used to collect the data from users or provide a provision for user to control the user interface. Forms are great potential assets if correctly used in building an interactive web application. We would be touch basing some of the essential aspects of them like HTML structure, styling form controls, events, data validation and submitting data to server.Understanding forms in detail needs expertise in other areas than just HTML like styling form controls (CSS), scripting to validate or create custom controls (JavaScript).We would be referring or using libraries like Jquery (for document traversal, manipulation etc) and parsley (form validation library) to build better forms.A typical form’s HTML is made of HTML elements called as form controls like single or multiline text fields, dropdowns, checkboxes, button etc mostly created using element with specific type being set on Type attribute. These form controls can be programmed to add some validations to support specific values based on constraints set on them. These controls can be enriched to support accessibility for enabling the interaction for less privileged users.Let’s create a simple html page to build a form.           Learning Forms       All forms have to start with element which is container having the form fields user would interact with. All attributes of element are optional but for programming forms to capture data we need at least ‘action’ and ‘method’ attributes.action – is basically the URL where the form fields data would be sent to.method – corresponds to the HTTP method to submit the form data. Possible HTTP method names which can be set as values are post and get. And another value dialog is set when form is imbedded inside a .Note: Both formaction and formmethod can be overridden by button, input with type submit elements which we will learn as we go forward.Refer to this link to know more about form attributes.Let’s add a form element to our body with action (“”) and method(“get”). This implies that form will send a GET request to the current URL. If it is post then it would be a POST request to the URL in action. Add few fields to form say name, email and a submit button using with type being specified as text, email and submit respectively.Note: The tag is an empty element, meaning that it doesn't need a closing tag. Value attribute can be populated to set the default value.          Enter your name:                    Enter your email:                       Save and open the html in chrome or your preferred browser. Clicking on ‘Click me!’ should send a http get call with empty name and email.Note: We can use instead of with type as submit. The difference is that button can contain HTML content allowing to create a complex button whereas input allows only plain text.Let’s understand the Sending of form data.If we observer all the form fields again, we have added an attribute called ‘name’. This property is important to inform that which data is associated with which form field i.e. name/value pairs. Try adding some data to our fields rendering in html (say myName and first.last@email.com) and click submit button. You should see the data being sent as query parameters in the browser URL.?name=myName&email=first.last@email.com.Change the Form method value to POST instead of GET and send the submitted data by clicking the ‘Click me!’ button. You should be seeing Form Data being sent but the browser URL will not get update.name: myName email: first.last@email.comAll this while, we have our action method being set as empty. Replace this with another URL on server side say ‘/captureFormData’. Now on clicking submit button the data should be received by the script at ‘/captureFormData’ with key/value items contained in the HTTP request object.Note that each server-side language like Node.js, C# etc have their own way of handling the submitted form data. And this blog would not cover those topics and it is beyond the scope.Let’s refine our basic form structure with help of other HTML elements like , , etc. Though we used few of them in basic example. Let’s go little deep on them.Note: Nesting of form inside another form is unacceptable as it might result in unpredictable behavior. is a convenient way of grouping for sake of styling and semantic purpose. This control can be associated with so that some assistive technologies can read this legend and associate it with the controls inside the . Let’s understand this will an example:         Interested programming language                             JavaScript                                     CSharp                                     Java               When reading the above form by any screen readers, it will read as “Interested programming language JavaScript” for the first radio, “Interested programming language CSharp” and “Interested programming language Java” for second and third radio.Imagine if you have a long form with multiple fields. It would help to improve the usability if we can categorize/section them with the help of . It would even help to improve the accessibility of forms.Talking about accessibility, with the associated correctly with the via its for attribute (which contains the element's id attribute), a screenreader will read out something like "name, edit text" for below one.Enter your name: Another advantage of having label associated with input of type text, radio etc is they are clickable too.  If you click on a label then the associated input control will get the focus. If the input control is of type checkbox or radio, clicking on label will select the check box and radio. This will be useful as clickable area of checkbox or radio is small and having label gives provision to select it easily.Note: We can always associate multiple labels to a single input control but it is not a good idea as it will impact the accessibility and assistive technologies. along with can be used to separate the functionality in a form and group the same purpose elements like radio buttons.Here is an example of the same.               Contact information                   Title                                                                             Mr                                                                                                 Mrs                                                                               Name:                                                           E-mail:                                                           Password:                                                 Additional information                               Social type:                                 LinkedIn             Twitter             Instagram                                                 Phone number:                                                           Submit                   Every time you like to create an HTML form you need to start using element and  nesting all the content controls inside it. Most of the assistive technologies and browser plugins can help to discover elements and implement special hooks to make them easier to use.We have already some of the form elements like , , , , , and . Other common input types are button, checkbox, file, hidden, image, password, radio, reset, submit, and text.Input types.Attributes of Input.Few attributes on element help in validating the data like required, max, maxlength, min, minlength, multiple, pattern, step etc based on their respective type.Also other attributes on of type submit/image like formaction, formmethod, formnovalidate, formenctype etc helps in overriding the form level methods.ValidationBefore submitting the data to the server, it is important to perform some client side validation to avoid unwanted round trips. Client-side validation is needed but it is not a replacement to the server side validation. Advantage of having client side validation is to capture the invalid data and fix it immediately.Some of the important and popular checks which are most commonly used on client areField requiredSpecific data formatEnter valid email addressPassword and more…Let’s build a form with the above validation checks.                         Do you have experience in programming ?*                     Yes           No                             How many years of experience you have ?                                     What's your programming language?*                           TypeScript           Java           CSharp           Ruby           Go           Swift                             What's your company e-mail address?                             Cover letter                             Submit       Say, if we enter an value which is more than 40 in experience field. We should see an inbuilt error as shown below:All these validations and notifications are coming out of the box. Thanks to inbuilt functionality in control. Let’s see how we can perform validation of forms using JavaScript and take control of look and feel of error message.Most browsers support constraint validation API by providing few validation properties on HTML elements like , , , etc.validationMessage: we can customize this message if the control value failed validation otherwise it will return an empty string. It is dependent on other constraint i.e. willValidate and isValid.willValidate: If element is validated then it will be true otherwise false.validity: is the validity state of the element and it is dependent on other properties likepatternMatch for specified pattern attribute,tooLong and tooShort are for string fields based on maxLength and minLengthrangeOverflow and rangeUnderflow for numeric fields based on max and min attributestypeMatch for fields which are based on email or url.valid if all the validation constraints are metvalueMissing if the field is set as required.Along with properties, we do also have methods to perform validation like checkValidity() which returns true or false and setCustomValidity(message) is to set the message if the element is considered invalid. Also if the element is invalid then checkValidity will raise an event called invalid Event.Let’s create a simple form and customize the validation message.       Please enter an email address:             Submit     Add a script tag and customize the message as shown below:     const email = document.getElementById("mail");     email.addEventListener("input", function (event) {       if (email.validity.typeMismatch) {         email.setCustomValidity("I am expecting an e-mail address!");       } else {         email.setCustomValidity("");       }     });   Here we are listening to the input event on email field and checking if the validity on the control is valid or not and based on that we are setting the custom message.Here are we relying on inbuilt validation method. Let’s disable the validation at form level by with the help of ‘novalidate’ and take control over validation. This would mean the browser will not perform auto check on validation before sending the data. But still we have access to constraint validation API to perform validation ourself.Refine the above form to add few addition validation like required and minLength etc.               Please enter an email address:                             Submit     Let’s update the script to handle the validation     const form  = document.getElementsByTagName('form')[0];     const email = document.getElementById('mail');     const emailError = document.querySelector('#mail + span.error');     email.addEventListener('input', function (event) {       // Each time the user types something, we check if the form fields are valid.       if (email.validity.valid) {         // In case there is an error message visible, if the field is valid, we remove the error message.         emailError.textContent = ''; // Reset the content of the message         emailError.className = 'error'; // Reset the visual state of the message       } else {         // If there is still an error, show the correct error         showError();       }     });     form.addEventListener('submit', function (event) {       // if the email field is valid, we let the form submit       if(!email.validity.valid) {         // If it isn't, we display an appropriate error message         showError();         // Then we prevent the form from being sent by cancelling the event         event.preventDefault();       }     });     function showError() {       if(email.validity.valueMissing) {         // If the field is empty display the following error message.         emailError.textContent = 'You need to enter an e-mail address.';       } else if(email.validity.typeMismatch) {         // If the field doesn't contain an email address display the following error message.         emailError.textContent = 'Invalid value is entered, expected an e-mail address.';       } else if(email.validity.tooShort) {         // If the data is too short display the following error message.         emailError.textContent = Email should be at least ${ email.minLength } characters; you entered${ email.value.length }.;       }       // Set the styling appropriately       emailError.className = 'error active';     } Reload the HTML and try entering an invalid email address, the corresponding error message should be displayed.Note: In the current scope of this blog, we are not working on styling.Is it possible to validate forms without built in APIs ? Let’s see with the same example.We would consider the same form again but have lot of functionality in                           Please enter an email address:                                             Submit           const form  = document.getElementsByTagName('form')[0];     const email = document.getElementById('mail');     let error = email.nextElementSibling;     const emailRegExp = /^[a-zA-Z0-9.!#$%&'*+/=?^_{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;     function addEvent(element, event, callback) {       let previousEventCallBack = element["on"+event];       element["on"+event] = function (e) {         const output = callback(e);         // A callback that returns false stops the callback chain and interrupts the execution of the event callback.         if (output === false) return false;         if (typeof previousEventCallBack === 'function') {           output = previousEventCallBack(e);           if(output === false) return false;         }       }     };     // Now we can rebuild our validation constraint. Because we do not rely on CSS pseudo-class, we have to explicitly set the valid/invalid class on our email field     addEvent(window, "load", function () {       // Here, we test if the field is empty (remember, the field is not required)       // If it is not, we check if its content is a well-formed e-mail address.       const test = email.value.length === 0 || emailRegExp.test(email.value);       email.className = test ? "valid" : "invalid";     });     // This defines what happens when the user types in the fiel     addEvent(email, "input", function () {       const test = email.value.length === 0 || emailRegExp.test(email.value);       if (test) {         email.className = "valid";         error.textContent = "";         error.className = "error";       } else {         email.className = "invalid";       }     });     // This defines what happens when the user tries to submit the data     addEvent(form, "submit", function () {       const test = email.value.length === 0 || emailRegExp.test(email.value);       if (!test) {         email.className = "invalid";         error.textContent = "Expecting an e-mail";         error.className = "error active";         return false;       } else {         email.className = "valid";         error.textContent = "";         error.className = "error";       }     });   On refreshing the page, the output with invalid email address should be displayed as shown below.In real time applications, we can rely on existing libraries like Parsley along with JQuery which would ease our life by taking away lot of complexity.Overview of Parsley:Parsley is a front-end javascript validation library which helps to give proper feedback to user on submission of form. As mentioned earlier, it is not a replacement of server side validation. Parsley library helps us to define our own validation.Parsley uses a DOM API namely ‘data-parsley-’ prefix on the existing properties. For example if we want to add this on a property say ‘sample’ then we would add as [data-parsley-sample=’value’]. This will allow us to configure pretty much everything without any configuration or custom function.There is no specific installation process but adding the corresponding script tags will enable the validation. Parsley is relied on Jquery so it has to be included as well.             ...                 $('#form').parsley(); Assumption is that we have downloaded the Jquery and Parsley minified librarie and added it to our working directory. Otherwise we can refer to CDN location as shown below. Adding attribute ‘data-parsley-validate’ to each form will allow us to validate. And “$(‘#form’).parsley()” will manually bind Parsley to your forms.Let’s understand further by configuring the attributes via JavaScript. For which, lets add two input fields inside the form element.                 Also let’s update the content to perform some pre-defined validation based on attributes.       var instance = $('#first').parsley(); console.log(instance.isValid()); // maxlength is 42, so field is valid$('#first').attr('data-parsley-maxlength', 4);       console.log(instance.isValid()); // No longer valid, as maxlength is 4       // You can access and override options in javascript too:       instance.options.maxlength++;       console.log(instance.isValid()); // Back to being valid, as maxlength is 5       // Alternatively, the options can be specified as:       var otherInstance = $('#second').parsley({ maxlength: 10 }); console.log(otherInstance.options); In the console.log, we should see thistrue false true {maxlength: 10}Options are inherited from the global level to form level and further to field. So if we set the options at global level then the same can be observed at field level. Parsley.options.maxlength = 42; // maxlength of 42 is declared at global level var formInstance =$('form').parsley(); var field = $('input').parsley(); console.log(field.options.maxlength); // Shows that maxlength is 42 inherited from global Parsley.options.maxlength = 30; console.log(field.options.maxlength); // Shows that maxlength is automatically 30 formInstance.options.maxlength++; console.log(field.options.maxlength); // Shows that maxlength is automatically 31We can also add our own custom validations. Let understand this with an example. window.Parsley.addValidator('multipleOf', { requirementType: 'integer', validateNumber: function(value, requirement) { return 0 === value % requirement; }, messages: { en: 'This value should be a multiple of %s', } }); Here we are adding a new attribute namely ‘data-parsley-multiple-of’ which takes only numeric values which are multiples of 3.In window.Parsley, we added a new validator with name ‘multiple-of’ with an object containing few important properties like ‘requirementType’, ‘validateNumber’ and ‘messages’ to be shown. This properties helps the library to check if the input value is valid or not.Similar to validateNumber, other properties are also there for different types like validateString, validateDate and validateMultiple.Also for requirementType, we have different options like string, number, date, regexp, boolean etc.Messages by default has English format, to support multiple locales we need to add the specific localization and also add specific locale.Events: Parsley triggers events that allows ParsleyUI to work and for performance reasons they don’t rely on JQuery events but the usage is similar to JQuery i.e. parsley events will also bubble up like JQuery events. For example, if a field is validated then the event ‘field:validate’ will be triggred on the field instance then on to form instance and finally to the window.Parsley.$('#some-input').parsley().on('field:success', function() {         // In here, this` is the parlsey instance of #some-input       });       window.Parsley.on('field:error', function() {         // This global callback will be called for any field that fails validation.         console.log('Validation failed for: ', this.$element); });Many times, we need some validation based on the response from server. Parsley provides an attributes i.e. data-parsley-remote and data-parsley-remote-validator to perform the same.Let’s consider this HTMLLet’s add the async validator on the window.Parsley object.window.Parsley.addAsyncValidator('customValidator', function (xhr) { console.log(this.$element); // jQuery Object[ input[name="q"] ]           return 404 === xhr.status;         }, 'customURL');Parsley is a very useful and powerful JavaScript form frontend validation library.Note: For developers building react based web applications, they can rely on FORMIK which is most popular library for building forms in React and React Native.ConclusionForms are important in HTML and it was needed and still needed now. is an html tag that allow us to perform HTTP methods like GET/POST operation without writing any code in JavaScript. Form defines an boundary to identify all set of the form field elements to be submitted to the server. For example, if we perform an enter key or clicking on submit button , the agent triggers form submission data based on each form field value to the server based on the action URL on the form.Before HTML5, all the elements are expected to be part of the to send the data to server. In HTML5, they maintained the backward compatibility and also enhanced the capabilities who may want to use AJAX and don’t want to rely on default behaviours i.e. they have enabled designers who expect more flexibility in having their form elements outside the form and still maintain the connections with the form.
1680
How to Work With Forms In JavaScript

Forms also referred as web forms are a very import... Read More