Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js DNS lookup - how to set timeout?

I'm very new to Node.js and I'm having an issue using node.dns.resolveNs function.

Some domains are completely down and it takes about a minute to get the response, which is usually "queryNs ETIMEOUT". Is there a way for me to set it to a shorter period, for example 10 seconds?

like image 336
Salmon Avatar asked May 27 '12 22:05

Salmon


1 Answers

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' ]
like image 85
Michelle Tilley Avatar answered Sep 19 '22 17:09

Michelle Tilley