Gracefully Kill Node.js App from Ctrl+C

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();
    });
  });
});
Tags: #nodejs #cli
Thomas Hunter II Avatar

Thomas has contributed to dozens of enterprise Node.js services and has worked for a company dedicated to securing Node.js. He has spoken at several conferences on Node.js and JavaScript, published a book on microservices, and is an organizer of Nodeschool SF.