I've been trying to perform an asynchronous operation before my process is terminated.
Saying 'terminated' I mean every possibility of termination:
ctrl+c
- Uncaught exception
- Crashes
- End of code
- Anything..
To my knowledge the exit
event does that but for synchronous operations.
Reading the Nodejs docs i found the beforeExit
event is for the async operations BUT :
The 'beforeExit' event is not emitted for conditions causing explicit termination, such as calling
process.exit()
or uncaught exceptions.The 'beforeExit' should not be used as an alternative to the 'exit' event unless the intention is to schedule additional work.
Any suggestions?
You can trap the signals and perform your async task before exiting. Something like this will call terminator() function before exiting (even javascript error in the code):
Add detail requested in comment:
Combining answers + handling for uncaught exceptions and promise rejections
Using beforeExit hook