Node.js DNS lookup - how to set timeout?

Node.js dns.resolve* use c-ares library underneath, which supports timeouts and various other options natively. Unfortunately Node.js doesn't expose those tunables, but some of them can be set via RES_OPTIONS environment variable.

Example: RES_OPTIONS='ndots:3 retrans:1000 retry:3 rotate' node server.js

  • ndots: same as ARES_OPT_NDOTS
  • retrans: same as ARES_OPT_TIMEOUTMS
  • retry: same as ARES_OPT_TRIES
  • rotate: same as ARES_OPT_ROTATE

See man ares_init_options(3) for details what each option means, for instance here http://manpages.ubuntu.com/manpages/zesty/man3/ares_init_options.3.html


I am not sure of any way to set a timeout directly on the function call, but you could create a small wrapper around the call to handle timing out yourself:

var dns = require('dns');

var nsLookup = function(domain, timeout, callback) {
  var callbackCalled = false;
  var doCallback = function(err, domains) {
    if (callbackCalled) return;
    callbackCalled = true;
    callback(err, domains);
  };

  setTimeout(function() {
    doCallback(new Error("Timeout exceeded"), null);
  }, timeout);

  dns.resolveNs(domain, doCallback);
};

nsLookup('stackoverflow.com', 1000, function(err, addresses) {
  console.log("Results for stackoverflow.com, timeout 1000:");
  if (err) {
    console.log("Err: " + err);
    return;
  }
  console.log(addresses);
});

nsLookup('stackoverflow.com', 1, function(err, addresses) {
  console.log("Results for stackoverflow.com, timeout 1:");
  if (err) {
    console.log("Err: " + err);
    return;
  }
  console.log(addresses);
});

The output for the above script:

Results for stackoverflow.com, timeout 1:
Err: Error: Timeout exceeded
Results for stackoverflow.com, timeout 1000:
[ 'ns1.serverfault.com',
  'ns2.serverfault.com',
  'ns3.serverfault.com' ]