timeout.js
1.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
/*!
* Connect - timeout
* Ported from https://github.com/LearnBoost/connect-timeout
* MIT Licensed
*/
/**
* Module dependencies.
*/
var debug = require('debug')('connect:timeout');
/**
* Timeout:
*
* Times out the request in `ms`, defaulting to `5000`. The
* method `req.clearTimeout()` is added to revert this behaviour
* programmatically within your application's middleware, routes, etc.
*
* The timeout error is passed to `next()` so that you may customize
* the response behaviour. This error has the `.timeout` property as
* well as `.status == 408`.
*
* @param {Number} ms
* @return {Function}
* @api public
*/
module.exports = function timeout(ms) {
ms = ms || 5000;
return function(req, res, next) {
var id = setTimeout(function(){
req.emit('timeout', ms);
}, ms);
req.on('timeout', function(){
if (req.headerSent) return debug('response started, cannot timeout');
var err = new Error('Request timeout');
err.timeout = ms;
err.status = 408;
next(err);
});
req.clearTimeout = function(){
clearTimeout(id);
};
res.on('header', function(){
clearTimeout(id);
});
next();
};
};