0

I have two different Nodejs servers in two different components, but they run in the same software together. When I close the program, i want both servers to exit gracefully, and free their respective TCP ports.

For each of them I have:

server1.js:

process.on('exit', function(){
    server.close();
});

server2.js:

process.on('exit', function(){
    server.close();
});

The problem is, that only one of these two functions runs with this method.

Closing them together in one function is not An option.

Is there anyway to add functions to the 'exit' event?

Makan
  • 2,508
  • 4
  • 24
  • 39

1 Answers1

3

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.

Estus Flask
  • 206,104
  • 70
  • 425
  • 565
  • Thanks for the info. In this case, it's not just servers to be closed. These components run in child processes, run in Dockers Containers, ... I might wanna write multiple exit messages on behalf of components.. I need a ubiquitous solution to stack all these tasks together. – Makan Oct 06 '18 at 13:35
  • It's unknown why callbacks don't run in your case. I would expect that they run but asynchronous calls don't have time to be completed. For a cleanup on Node exit in general, see https://stackoverflow.com/questions/14031763/doing-a-cleanup-action-just-before-node-js-exits . I'm using a recipe similar to the answer myself. This depends on how you end the process. You won't have time to do a cleanup on `process.exit()` call, for instance. – Estus Flask Oct 06 '18 at 13:51