0

https://nodejs.org/api/process.html

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. In the following example, for instance, the timeout will never occur:

process.on('exit', (code) => {
  setTimeout(() => {
    console.log('This will not run');
  }, 0);
});

Now I have this in my main.js:

if (errors) {
    process.exitCode = 1;
}
process.emit("exit");

In a logger that has shutdown listeners etc I have a mongo connection and the following:

    process.on("exit", (code) => {
        if (this.status.finishedAt === null) {
            this.status.currentState = StatusUpdater.STATE_STOPPED;
            this.status.finishedAt = new Date();
            this.persistStatus()
            .then(() => {
                this.mongoDb.close().then(() => {
                    setTimeout(() => {
                        console.log('byebye');
                        process.exit(code);
                    }, 5000);
                });
            })
            .catch(this.noMongoConnection);
        }
    });

The output is: byebye after 5 seconds.

Now I am confused. Obviously I can do asyncronous operations after the exit event is triggered. The manual says this is not possible.

What is right and what is wrong?

Daniel W.
  • 31,164
  • 13
  • 93
  • 151
  • Calling `process.exit(code);` inside the `exit` event handler is very weird. I wonder whether this will actually trigger all your handlers twice. – Bergi Mar 08 '17 at 15:12
  • @Bergi it does, so I check for the `finishedAt` is not undefined. Also when you trigger a `SIGINT`, the `exit` event is also called afterwards. – Daniel W. Mar 08 '17 at 15:34
  • @Bergi Do you have an idea for a shutdown handler other than how I did it? The only downside of my solution is that when there is another exit listener and has a chance not to be executed when I do the `process.exit()` before that other listener. – Daniel W. Mar 08 '17 at 15:37
  • Admittedly I have no idea what the best practice is, but I would at least use a different event name for the asynchronous exit handlers. And I would not call `process.exit(1)` from the mongodb handler, but from the place where I'd fire the shutdown event. – Bergi Mar 08 '17 at 15:44

1 Answers1

1

That is because you are manually emitting an event with the name exit, which does not cause any special behaviour by itself. Only if you used process.exit as in

if (errors)
    process.exit(1);

it would have the effects described in the documentation.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • The difference between calling `.exit()` and emitting the `exit` event should be clearer in the docs but your answer helps to understand it's not the same. – Daniel W. Mar 08 '17 at 15:36