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. :)

1

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

@murvinlal slightly less efficient then using the native timeouts but not noticeably slower, should be fine for efficiency.
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 Raynos
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', ...);
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.