Node.js DNS查询 – 如何设置超时?
我对Node.js非常陌生,使用node.dns.resolveNs函数时遇到了问题。
有些域完全closures,大概需要一分钟才能得到响应,通常是“queryNs ETIMEOUT”。 有没有办法让我把它设置为一个较短的时间,例如10秒?
我不确定直接在函数调用上设置超时的方法,但是你可以在调用的时候创build一个小的包装来处理超时:
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); });
上述脚本的输出:
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' ]
Node.js dns.resolve*
使用下面的c-ares库,它支持本地超时和其他各种选项。 不幸的是,Node.js不公开这些可调参数,但其中一些可以通过RES_OPTIONS
环境variables来设置。
示例: RES_OPTIONS='ndots:3 retrans:1000 retry:3 rotate' node server.js
-
ndots
:与ARES_OPT_NDOTS相同 -
retrans
:与ARES_OPT_TIMEOUTMS相同 -
retry
:与ARES_OPT_TRIES相同 -
rotate
:与ARES_OPT_ROTATE相同
有关详细信息,请参见man ares_init_options(3),例如http://manpages.ubuntu.com/manpages/zesty/man3/ares_init_options.3.html