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: #cli #nodejs
Thomas Hunter II Avatar

Thomas is the author of Advanced Microservices and is a prolific public speaker with a passion for reducing complex problems into simple language and diagrams. His career includes working at Fortune 50's in the Midwest, co-founding a successful startup, and everything in between.