4

Is there a way to execute a piece of code in Node.js Express just before the node.js process exits, regardless whether it was due to an error being thrown, or pressing Ctrl+C, or any other reason?

1 Answer 1

9

You're looking for the exit event. From the documentation:

Emitted when the process is about to exit. This is a good hook to perform constant time checks of the module's state (like for unit tests). The main event loop will no longer be run after the 'exit' callback finishes, so timers may not be scheduled.

And it would be implemented as

process.on('exit', function() {
    console.log('About to close');
});

It's worth mentioning, that it's generally not a good idea to try to manipulate data if you don't know the reason for the exit or exception. If you don't know what's wrong, it's usually a better idea to start fresh, than try to accomplish something with something that may very well be FUBAR.

Sign up to request clarification or add additional context in comments.

3 Comments

f@#$ed up beyond all recognition/repair/reason.
I managed to acheive what I want with: process.on('SIGINT', function() {.
I made with process.on('SIGTERM'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.