Is there a way to execute a piece of code in Node.js Express just before the node.js process exits, regardless whether it was due to an error being thrown, or pressing Ctrl+C, or any other reason?
You're looking for the exit event. From the documentation:
Emitted when the process is about to exit. This is a good hook to perform constant time checks of the module's state (like for unit tests). The main event loop will no longer be run after the 'exit' callback finishes, so timers may not be scheduled.
And it would be implemented as
process.on('exit', function() {
console.log('About to close');
});
It's worth mentioning, that it's generally not a good idea to try to manipulate data if you don't know the reason for the exit or exception. If you don't know what's wrong, it's usually a better idea to start fresh, than try to accomplish something with something that may very well be FUBAR.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With