Daniel W.
Daniel W.

Reputation: 32290

`exit` event in node.js behaves different than in the manual

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?

Upvotes: 0

Views: 488

Answers (1)

Bergi
Bergi

Reputation: 664513

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.

Upvotes: 1

Related Questions