Node.js: how to perform a DNS query

Node.js: how to perform a DNS query

In this article we will see how to perform DNS queries in Node.js.

In this article we will see how to perform DNS queries in Node.js.

We can use the Resolver class of the core dns module which allows us not only to perform queries asynchronously but also to set the reference nameservers on which to perform these queries.

We can define the following wrapper class.


	'use strict';

	const { Resolver } = require('dns').promises;
	const resolver = new Resolver();
	const nameservers = ['8.8.8.8', '8.8.4.4'];
	const validator = require('validator');
	
	resolver.setServers(nameservers);
	
	class DNSCheck {
		constructor({ host, recordType }) {
			this.host = host;
			this.recordType = recordType;
			this.recordTypes = ['A', 'AAAA', 'CAA', 'CNAME', 'MX', 'NAPTR', 'NS', 'PTR', 'SOA', 'SRV', 'TXT'];
		}
	
		async check() {
			if(!this.isValidHost(this.host) || !this.isValidRecordType(this.recordType)) {
				return { error: 'Invalid parameters.' };
			}
	
			try {
				const result = await  resolver.resolve(this.host, this.recordType);
				return { result };
			} catch(err) {
				return { error: 'Record not found.' };
			}
		}
	
		isValidRecordType(value) {
			return this.recordTypes.includes(value);
		}
		isValidHost(value) {
			if(typeof value !== 'string') {
				return false;
			}
	
			return validator.isFQDN(value);
		}
	}
	
	module.exports = DNSCheck;	
	

A possible use from the command line could be for example as follows.


	'use strict';

	const DNSCheck = require('./lib/DNSCheck');
	
	const checkDNS = async () => {
		const args = process.argv;
		if(args.length !== 4) {
			console.log('Usage: node  index HOSTNAME RECORD');
			process.exit(1);
		}
		const [host, recordType] = args.slice(2);
		const dnsCheck = new DNSCheck({
			host,
			recordType
		});
	
		try {
			const results = await dnsCheck.check();
			console.log(results);
		} catch (err) {
			console.log(err.message);
		}
	
	};
	
	checkDNS();