Reputation: 113
I'm writing a node.js application that needs to talk to a server. It establishes an http connection with the following code:
var client = http.createClient(u.port, u.hostname, u.secure);
client.on("error", function(exception) {
logger.error("error from client");
});
var request = client.request(method, u.path, headers);
I don't see any option in the node.js documentation for setting a timeout on the connection, and it seems to be set to 20 seconds by default. The problem I'm having is that I have users in China on what appears to be a slow or flaky network, who sometimes hit the timeout connecting to our datacenter in the US. I'd like to increase the timeout to 1 minute, to see if that fixes it for them.
Is there a way to do that in node.js?
Upvotes: 11
Views: 36046
Reputation: 8554
There is no capability in Node to increase connect timeout. Since usually connect timeout (i.e. connection establishing timeout) is OS-wide setting for all applications (e.g., 21 seconds in Windows, from 20 to 120 seconds in Linux). See also Timouts in Request package.
In contrast, Node allows to set decreased timeout and abort connecting even in case when the connection is not yet established.
The further timeouts (in case of connection has been established) can be controlled according to the documentation (see request.setTimeout
, socket.setTimeout
).
Upvotes: 4
Reputation: 3539
You have to wait for the client socket connection to be established first, before setting the timeout. To do this, add a callback for the 'socket' event:
req.on('socket', function (socket) {
myTimeout = 500; // millis
socket.setTimeout(myTimeout);
socket.on('timeout', function() {
console.log("Timeout, aborting request")
req.abort();
});
}).on('error', function(e) {
console.log("Got error: " + e.message);
// error callback will receive a "socket hang up" on timeout
});
Upvotes: 2
Reputation: 37133
I think you can do something like:
request.connection.setTimeout(60000)
request.connection returns the net.Stream object associated with the connection. and net.Stream has a setTimeout method.
Upvotes: 4