How to set Timeout for http.createClient in Node.js?
Asked Answered
T

2

5

There is a post: How do I set a timeout for client http connections in node.js

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();

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.

However, I haven't seen any timeout features in the documentation for http.createClient. Please advise. Thanks. :)

Tokenism answered 25/5, 2011 at 18:41 Comment(1)
See answers in this duplicate question: #6215402 (especially see douwe's answer)Skintight
S
6
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.

Scent answered 25/5, 2011 at 18:57 Comment(3)
@murvinlal slightly less efficient then using the native timeouts but not noticeably slower, should be fine for efficiency.Scent
github.com/mikeal/request/issues/25 - this library is built on top of http/client so it sounds like its not really a feature in nodes core http client -- agree with RaynosSharlenesharline
Thanks. I also have a question. for the code, it set the timeout for the request. Do I need to set another timeout handler for response? e.g response.addListener('data', ... ); and add one like that: response.on('data-timeout', ...);Tokenism
K
0

The answer above is old. http.request now accepts a timeout option in:

http.request(options[, callback])
http.request(url[, options][, callback])

From the doc:

timeout : A number specifying the socket timeout in milliseconds. This will set the timeout before the socket is connected.

Kahaleel answered 31/3, 2024 at 9:38 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.