如何在 Node.js 中为 http.createClient 设置超时? [英] How to set Timeout for http.createClient in Node.js?
本文介绍了如何在 Node.js 中为 http.createClient 设置超时?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有个帖子:如何在 node.js 中为客户端 http 连接设置超时
但没有一个答案行得通.
but none of the answer will work.
所以,我有这样的代码:
So, I have the code like that:
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 秒.如果是,则触发侦听器.
The biggest problem is that the url that I'm connection to may timeout. Therefore, I would like to set a timeout, like 15 secs. If so, trigger a listener.
但是,我在 http.createClient 的文档中没有看到任何超时功能.请指教.谢谢.:)
However, I haven't seen any timeout features in the documentation for http.createClient. Please advise. Thanks. :)
推荐答案
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);
});
您自己去柜台办理即可.
Just run the counter yourself.
这篇关于如何在 Node.js 中为 http.createClient 设置超时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文