Search code examples
node.jsdns

How to increase the timeout time on dns.resolve4() in Node.js?


How do I increase the timeout time of the dns resolution in Node.js? I'm trying to resolve url's to see what is available, but a lot of requests are timing out and maybe false positives.

// checks a url string for availability and errors on 'err'
function checkAvailable( url ) {
  dns.resolve4( url, function (err, addresses) {
    if (err) console.log (url + " : " + err)
  })
}

Solution

  • The Node.js DNS module is a wrapper around c-ares and is pretty thin on options. If you need to provide any (such as a timeout), I would recommend looking at node-dns, which provides a 1:1 mapping for all the functions available in the DNS module, plus additional methods for specifying more advanced options (including timeouts):

    var dns = require('native-dns');
    
    var question = dns.Question({
      name: 'www.google.com',
      type: 'A'
    });
    
    var req = dns.Request({
      question: question,
      server: { address: '8.8.8.8', port: 53, type: 'udp' },
      timeout: 1000
    });
    
    req.on('timeout', function () {
      console.log('Timeout in making request');
    });
    
    req.on('message', function (err, answer) {
      answer.answer.forEach(function (a) {
        console.log(a.promote().address);
      });
    });
    
    req.on('end', function () {
      console.log('Finished processing request');
    });
    
    req.send();