Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to send reponse when timeout in node.js http module

On nodejs.org socket.setTimeout, it says

When an idle timeout is triggered the socket will receive a 'timeout' event but the connection will not be severed.

But when I test code like this:

var http = require('http');

server = http.createServer(function (request, response) {
    request.socket.setTimeout(500);
    request.socket.on('timeout', function () {
        response.writeHead(200, {'content-type': 'text/html'});
        response.end('hello world');
        console.log('timeout');
    });
});

server.listen(8080);

The socket is closed immediately after timeout, and no data is replied to the browser. Which is quite different from the document. Is this a bug or is there any tricks dealing socket under http module?

like image 289
Jack Avatar asked Jun 10 '26 00:06

Jack


1 Answers

The documentation is indeed correct, however it looks like the http module adds a 'timeout' listener which calls socket.destroy(). So what you need to do is get rid of that listener by calling request.socket.removeAllListeners('timeout'). So your code should look like:

var http = require('http');

server = http.createServer(function (request, response) {
    request.socket.setTimeout(500);
    request.socket.removeAllListeners('timeout'); 
    request.socket.on('timeout', function () {
        response.writeHead(200, {'content-type': 'text/html'});
        response.end('hello world');
        console.log('timeout');
    });
});

server.listen(8080);
like image 184
Aaron Avatar answered Jun 13 '26 04:06

Aaron



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!