Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save thomas-riccardi/483cd9644b9160fe4d46 to your computer and use it in GitHub Desktop.
Save thomas-riccardi/483cd9644b9160fe4d46 to your computer and use it in GitHub Desktop.
HTTP Server request.setTimeout(n, cb) partially applies globally
var http = require('http');
var timeout = 100;
var port = 3000;
console.log('Test HTTP Server with timeout on Server, Request, Response & socket destroy: unexpected timeout');
var server = http.createServer(function(req, res) {
console.log('server', 'got request');
// 2/ set a request timeout with a listener that *won't* be called because the request part will finish before
req.setTimeout(timeout, function() {
console.log('server', 'request timeout');
res.end('server hello from request timeout');
});
// 3/ delay normal response to after the request timeout
setTimeout(function() {
console.log('server', 'delayed response');
res.end('server hello from delayed response');
}, timeout*2);
}).listen(port, function() {
console.log('client', 'sending request');
var req = http.request({port: port}, function(res) {
console.log('client', 'got response');
res.on('data', function (chunk) {
console.log('client', 'reponse', 'data:', chunk.toString());
});
res.on('finish', function () {
console.log('client', 'response', 'finish');
});
});
req.on('error', function(e) {
console.log('client', 'error', e);
});
req.end();
});
// 1/ disable default global timeout
server.setTimeout(0);
// cleanup
setTimeout(function() {
console.log('exit');
process.exit();
}, timeout*3);
/** Results:
client sending request
server got request
client error { [Error: socket hang up] code: 'ECONNRESET' }
server delayed response
**/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment