Node.js process exit
event can have multiple listeners.
This
process
.on('exit', () => console.log('foo'))
.on('exit', () => console.log('bar'));
should result in
foo
bar
output.
Closing Node.js web servers explicitly is unnecessary because they will be closed any way on process exit.
exit
event listener is not a proper place to close connections in general because this is usually asynchronous process. exit
listener is supposed to be synchronous:
Listener functions must only perform synchronous operations. The Node.js process will exit immediately after calling the 'exit' event listeners causing any additional work still queued in the event loop to be abandoned.
While beforeExit
event listener may be skipped in some cases but is suitable for asynchronous operations:
The 'beforeExit' event is emitted when Node.js empties its event loop
and has no additional work to schedule. Normally, the Node.js process
will exit when there is no work scheduled, but a listener registered
on the 'beforeExit' event can make asynchronous calls, and thereby
cause the Node.js process to continue.
<...>
The 'beforeExit' event is not emitted for conditions causing explicit
termination, such as calling process.exit() or uncaught exceptions.