Reputation: 12997
I have user http.request
for making connection to another server in nodejs. Unfortunately that server has a delay in responding in some situations. So I want to close the request after some period.
I have found following code but this close connection if target server was not reachable or connection has not been established.
req.on('socket', function (socket) {
socket.setTimeout(myTimeout);
socket.on('timeout', function() {
req.abort();
});
});
What I want is closing connection after for example 2 seconds wether data is coming or not.
Does anyone has any idea?
Upvotes: 1
Views: 598
Reputation: 24541
I don't really know the sockets library you use, maybe it has some ready and nice solution for that as well, but it looks simple to just use setTimeout
function:
req.on('socket', function (socket) {
setTimeout(function() {
// maybe some additional condition here
// or recursive call if you want to wait 2 more seconds
// or whatever else
// but if you want to just abort...
req.abort();
}, 2000);
});
Again, this maybe looks like a workaround, but it definitely should be enough as I understand from your request.
Upvotes: 1