In this article we will see how to perform DNS queries with the dig command in Node.js.
Let's create a class that accepts the domain name and the record type as its constructor's parameters.
'use strict';
const { exec } = require('child_process');
class Dig {
constructor(domain, record) {
this.domain = domain;
this.record = record;
this.cmd = `dig +nocmd ${this.domain} ${this.record} +noall +answer`;
}
lookup() {
const self = this;
return new Promise(( resolve, reject ) => {
exec(self.cmd, (error, stdout, stderr) => {
if(error || stderr) {
reject('DNS lookup failed');
}
resolve(stdout);
});
});
}
}
module.exports = Dig;
exec()
from the core module child_process
will execute the dig
command on the shell.
By using Promises we can handle the output returned from the shell and any kind of errors that may result.
Finally we can use this class in our application.
'use strict';
const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
const port = process.env.PORT || 3000;
const app = express();
const Dig = require('./lib/Dig');
app.disable('x-powered-by');
app.use('/public', express.static(path.join(__dirname, '/public'), {
maxAge: 0,
dotfiles: 'ignore',
etag: false
}));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname) + '/views/index.html');
});
app.post('/api/lookup', async (req, res) => {
const { domain, type } = req.body;
const dig = new Dig(domain, type);
try {
const lookup = await dig.lookup();
res.send(lookup);
} catch(err) {
res.send(err);
}
});
if (app.get('env') === 'development') {
app.use((err, req, res, next) => {
res.status(err.status || 500);
});
}
app.use((err, req, res, next) => {
res.status(err.status || 500);
});
app.listen(port);