How to cancel request and return a timeout error if request takes more than a particular time in Nodejs

246 Views Asked by At

I want to write an API in Nodejs which will return an error if the excution takes more than a particular time otherwise will proceed normally. How to do that?? Regards, Abdul

1

There are 1 best solutions below

0
David Shiref On

The node thread needs to co-operate by clearing everything that is running on the event loop and then it terminates naturally by returning. So just stop listening for requests, close handles etc. You can use process._getActiveRequests and process._getActiveHandles to see what is keeping the event loop alive.

You can also abruptly interrupt the node thread just by calling OS apis but this will leak a lot of garbage until you exit the process so you cannot start/restart node a lot of times before you need to exit the process anyway to free the leaked resources.