Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need to reduce the timeout period for a route in expressjs

Within expressjs is there a way I can set the timeout limit per route.

I have some routes that may take 30-45 seconds to process (A large amount of tasks)

And then other routes that if it takes longer than 5 seconds I want it to time out.

I guess I am asking is there a way to globally set the timeout limit on requests and is there a way to do it individually on routes.

like image 832
nwkeeley Avatar asked Jan 18 '13 22:01

nwkeeley


People also ask

How do I set timeout in Express?

You can try: return await new Promise((resolve) => setTimeout(() => { resolve(resp); }, 3000), ); In above code, 3000 = 3 sec. Change it according to your requirement.

How to handle timeout in NodeJS?

I noticed that in the timeout event both the 'abort' event is triggered and the request callback is called, in this order, so I used the setTimeout function to wait for the request callback and than handle the error in the 'abort' listener.

What is the default timeout for NodeJS?

In Node. js, default server timeout is 0 milliseconds for the latest version and 2min i.e. (120000 milliseconds) for the older version.


1 Answers

Use the built-in connect-timeout middleware:

http://www.senchalabs.org/connect/timeout.html

var connectTimeout = require('connect-timeout');

var timeout = connectTimeout({ time: 10000 });
var longTimeout = connectTimeout({ time: 45000 });

app.use(timeout); // you can set a global timeout value
app.get('/some/route', longTimeout, yourHandler); // or you can set per-route timeouts
like image 165
hunterloftis Avatar answered Sep 19 '22 14:09

hunterloftis