Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute code on nodejs server shutdown with express

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?

like image 831
Martin Taleski Avatar asked Oct 17 '25 18:10

Martin Taleski


1 Answers

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.

like image 174
Robert Avatar answered Oct 20 '25 07:10

Robert



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!