Often times, we run a Node.js app directly from the command line while prototyping. To kill such a process from the command line, pressing Ctrl+C does the trick. Unfortunately, this causes the app to halt what it is doing and come to a halt, often throwing a few errors depending on the type of work we were in the middle of doing.
To prevent this from happening, we can make use of the available process object. This object is available in any running Node.js app, and doesn’t need a require statement.
Specifically, we will want to make use of both the on event handler for catching the SIGINT event (Signal Interrupt), as well as the exit method, which kills the app.
Check out the following code used in my node wireless module for a better explanation:
process.on('SIGINT', function() {
console.log("\nGracefully shutting down from SIGINT (Ctrl+C)");
console.log("Disabling Adapter...");
wireless.disable(function() {
console.log("Stopping Wireless App...");
wireless.stop(function() {
console.log("Exiting...");
process.exit();
});
});
});
Thanks for the tip! Needed to know this exact thing to close out a database connection on signal interruption and found your article straightaway. Thanks for using Ctrl+C in the title / URL, as I didn’t know the actual name for what I was doing. ; )