Search code examples
node.jssignalsexitterminate

Stopping Node.js gracefully


How to stop Node.js application gracefully?

I need to write my memory content into file, on receiving killing signals (e.g., SIGINT (2), SIGTERM (3)), before termination, so as to do a "graceful shutdown". How to do that?

PS. This is not the same question as Quitting node.js gracefully, as the question was wrong, doing ctrl+z instead of ctrl+c, and the answer doesn't cover handling killing signals.


Solution

  • You could listen to exit or SIGINT using

    process.on("exit", () => /* this will be called on the exit event */);
    
    
    process.on("SIGINT", () => /* this will be called on the SIGINT event */);