For Ctrl-C (which you have now added to your question), you can't do what you want to do. node.js does not have that feature.
Since the Ctrl-C is under your control, you could send a command to your server to do a normal shut-down and then it could do your asynchronous work and then call process.exit()
rather than you just typing Ctrl-C in the console. This is what many real servers do in production. They have a control port (that is not accessible from the outside world) that you can issue commands to, one of which would be to do a controlled shut-down.
Original answer
(before there was any mention of Ctrl-C being the shut-down initiation)
You can't run asynchronous operations on the exit
event (it's too late in the shutdown sequence).
You can run asynchronous operations on the beforeExit
event.
But, the beforeExit
event is only called if nodejs naturally exits on its own because it's queue of remaining work scheduled is empty (no open sockets, files, timers, etc...). It will not be called if the process exits abnormally (such as an unhandled exception or Ctrl-C) or if process.exit()
is called manually.
You can handle the case of manually calling process.exit()
by replacing the call to process.exit()
in your app with a call to a custom shutdown function that does your housekeeping work and then when that has successfully completed, you then call process.exit()
.