Request timeout middleware for Connect/Express
Times out a request in the Connect/Express application framework.
$ npm install connect-timeout
NOTE This module is not recommend as a "top-level" middleware (i.e.
app.use(timeout('5s'))) unless you take precautions to halt your own
middleware processing. See as top-level middleware
for how to use as a top-level middleware.
While the library will emit a 'timeout' event when requests exceed the given timeout, node will continue processing the slow request until it terminates. Slow requests will continue to use CPU and memory, even if you are returning a HTTP response in the timeout callback. For better control over CPU/memory, you may need to find the events that are taking a long time (3rd party HTTP requests, disk I/O, database calls) and find a way to cancel them, and/or close the attached sockets.
Returns middleware that times out in
time can also
be a string accepted by the ms
module. On timeout,
req will emit
timeout function takes an optional
options object that may contain
any of the following keys:
Controls if this module will "respond" in the form of forwarding an error.
true, the timeout error is passed to
next() so that you may customize
the response behavior. This error has a
.timeout property as well as
.status == 503. This defaults to
Clears the timeout on the request. The timeout is completely removed and will not fire for this request in the future.
true if timeout fired;
Because of the way middleware processing works, once this module passes the request to the next middleware (which it has to do in order for you to do work), it can no longer stop the flow, so you must take care to check if the request has timedout before you continue to act on the request.
var express = require'express';var timeout = require'connect-timeout';// example of using this top-level; note the use of haltOnTimedout// after every middleware; it will stop the request flow on a timeoutvar app = express;appusetimeout'5s';appusebodyParser;appusehaltOnTimedout;appusecookieParser;appusehaltOnTimedout;// Add your routes here, etc.if !reqtimedout next;applisten3000;
var express = require'express';var bodyParser = require'body-parser';var timeout = require'connect-timeout';var app = express;apppost'/save' timeout'5s' bodyParserjson haltOnTimedoutsavePostreqbodyif err return nexterr;if reqtimedout return;ressend'saved as id ' + id;;;if !reqtimedout next;setTimeoutcbnull Mathrandom* 40000 >>> 0;Mathrandom* 7000 >>> 0;applisten3000;
var bodyParser = require'body-parser';var connect = require'connect';var timeout = require'connect-timeout';var app = require'connect';appuse'/save' timeout'5s' bodyParserjson haltOnTimedoutsavePostreqbodyif err return nexterr;if reqtimedout return;ressend'saved as id ' + id;;;if !reqtimedout next;setTimeoutcbnull Mathrandom* 40000 >>> 0;Mathrandom* 7000 >>> 0;applisten3000;