I've been reading documentation and it's not explicitly stated whether the Node.js process immediately exits or not if no signal handler is registered. For example, are pending tasks in the poll queue executed or is everything dropped? Does the programmer always have to handle graceful shutdown explicitly by keeping track of all pending promises?
1 Answers
When no handler is added for SIGTERM
, node will reset the terminal and exit the process immediately. It's a "drop everything where it is" exit. Even more so than so than process.exit
which does still allow the exit
event to fire:
Calling
process.exit()
will force the process to exit as quickly as possible even if there are still asynchronous operations pending that have not yet completed fully, including I/O operations toprocess.stdout
andprocess.stderr
.
When a signal handler is added (process.once('SIGTERM')
, the handler code is scheduled for the next event loop. So behaviour immediately changes even if you just call process.exit()
in the handler.
Promises, or Javascript generally for that matter, don't have the concept of cancellation built in yet. You could track promises but unless the underlying API's being used specifically address ways to cancel tasks then there's not much to do.
You can just wait though. In the average web application if you close the web server and close the database connection. Existing connections will complete, no new connections will initiate, eventually the process will exit by itself when there is nothing left on the event loop to run. wtfnode
can be handy to help debug processes that aren't eventually exiting like this.

- 68,711
- 7
- 155
- 158
-
Thanks. I'm working on Discord bots, which function similarly to web applications except they respond to events coming from a WebSocket. Disconnecting works, however I don't think even with a web application that we can just drop the database connection on SIGTERM if requests being processed depend on the database. But if the database connection isn't dropped, the process won't exit properly until sent a second signal. Is there a solution or is requiring two signals to terminate acceptable and standard? – Kevin Lu Jan 13 '21 at 03:52
-
1It's usually best to assume your node process can go away at any time, because it can, and it should recover whatever was left behind at start up. Usually non atomic database updates need to be wrapped in a transaction. Some user transactions might need to be restartable. Maybe ask a question with a specific example(s) of something you are concerned with failing mid flight – Matt Jan 13 '21 at 05:15