You can intercept signals and perform an asynchronous task before exiting. Something like this will call the terminator () function before exiting (even a JavaScript error in the code):
process.on('exit', function () { // Do some cleanup such as close db if (db) { db.close(); } }); // catching signals and do something before exit ['SIGHUP', 'SIGINT', 'SIGQUIT', 'SIGILL', 'SIGTRAP', 'SIGABRT', 'SIGBUS', 'SIGFPE', 'SIGUSR1', 'SIGSEGV', 'SIGUSR2', 'SIGTERM' ].forEach(function (sig) { process.on(sig, function () { terminator(sig); console.log('signal: ' + sig); }); }); function terminator(sig) { if (typeof sig === "string") { // call your async task here and then call process.exit() after async task is done myAsyncTaskBeforeExit(function() { console.log('Received %s - terminating server app ...', sig); process.exit(1); }); } console.log('Node server stopped.'); }
Add details requested in comments:
- Signals explained in the node documentation , this link refers to standard POSIX signal names
- Signals must be string. However, I saw others do the check, so there may be some other unexpected signals that I donβt know about. I just want to make sure before calling process.exit (). I believe that verification will not take much time anyway.
- for db.close (), I think it depends on the driver you are using. Whether synchronization is asynchronous. Even if it is asynchronous and you do not need to do anything after closing db, then everything should be fine, because async db.close () just generates a close event, and the event loop will continue to process it, regardless of whether your server has finished or not.
source share