如何在Node.js中设置http.createClient的Timeout?

有一篇文章: 如何在node.js中为客户端http连接设置超时

但是没有一个答案会起作用。

所以,我有这样的代码:

var remote_client = http.createClient(myPost, myHost); var path = '/getData?'; var param = { }; var request = remote_client.request("POST", path,); // error case remote_client.addListener('error', function(connectionException){ console.log("Nucleus Error: " + connectionException); next(connectionException); }); request.addListener('response', function (response) { response.setEncoding('utf-8'); var body = ''; response.addListener('data', function (chunk) { // get the result! }); }); request.end(); 

最大的问题是,我连接到的URL可能超时。 所以我想设置一个15秒的超时时间。 如果是这样,触发一个监听器。

但是,我没有看到http.createClient文档中的任何超时function。 请指教。 谢谢。 🙂

 var foo = setTimeout(function() { request.emit("timeout-foo"); }, 15000); // listen to timeout request.on("timeout-foo", function() { }); request.addListener('response', function (response) { // bla // clear counter clearTimeout(foo); }); 

你自己去跑步吧