How to Quit Node earnanswers.com This image is a blog banner. It depicts personal code on the side and the node JS logo in the foreground.

How to Quit Node

Published: Updated: Programming tutorial en
Table of Content
  1. How to Quit from a Node REPL
  2. How to Quit Node: Article's Material
  3. How to Quit a Running Instance Part 2
  4. Explaining processes
  5. Process termination signals
    • SIGINT (Signal Interruption):
    • SIGTERM (Signal Terminate):
  6. Javascript Code to Quit Node JS instance
  7. How to instantiate a Node JS project
  8. Earnanswers Node JS project services

How to Quit from a Node REPL

To close a node REPL after you execute:

node

Use your keyboard CTRL + C (Cmd + C) to quit.

To exit from the REPL and re-enter the command line, you can also execute the command below:

process.exit()

How to Quit Node: Article's Material

Finding boilerplate code to quit a Node JS application properly is one of the most hidden information in the tutorial-verse.

In this article, I will show you how to close a web server instance using your keyboard (CTRL + C or Cmd + C).

Then, If you are looking for the best way to quit your Node JS web server instance, you are in the right place.

In this article, I will explain some process signal termination concepts, and finally, I will provide and explain the JavaScript code I use to close my Node JS instances.

Click here to access the code directly: node express boilerplate 2023. The tutorial to set up a Node JS project is in this blog article: Projet Node JS

The image depicts a terminal command line, and you see the command npm run start executed on the window. The command enables the view of a Node Express app instantiating. The image depicts a terminal command line, and you see the command npm run start executed on the window. The command enables the view of a Node Express app instantiating.

How to Quit a Running Instance Part 2

Then, when on the terminal, to quit your Node JS instance just hit CTRL + C from a macOS or Cmd + C from a Windows. This procedure will quit your local web server's process.

On quit, you can program a script to exit the running resources on your application. By exiting these running resources, you are making sure not to shut down the terminal process on those running resources abruptly.

It's like turning down your television before pulling out the power cord.

Explaining processes

In all Unix-like operating systems, a process is a running program. The program is controlled on the operating system level. The controls that take place are the amount of hardware resources the process can take optimally. The resources also comprise memory space.

By the OS, the process is given what is known as the process ID (PID). When you boot up an app on your computer, one or several processes start running depending on the app's needs. Also, processes run isolated from other processes so that they do not interfere with one another.

When you run a Node JS instance locally, a process for the Node JS application begins to run.

Process termination signals

Two main signals sent from the operating system kernel can get sent to a process for that process to quit.

SIGINT (Signal Interruption):

This signal is typically sent when a user presses Ctrl+C in the terminal. It's a way of telling the process to interrupt its current activity.

SIGTERM (Signal Terminate):

This is a more general termination signal designed to shut down a process.

Unlike SIGINT, which is usually triggered by user interaction, SIGTERM is generally sent from the system, I.e. processes or scripts.

For example, a SIGTERM signal can get triggered towards your Node JS process if your server reboots or gets shut down.

Javascript Code to Quit Node JS instance

Thankfully, in Node JS, you can program a signal handler to handle the termination signal. The handler executes commands before the process gets terminated.

Also, you can code how the process gets terminated, i.e., successfully or unsuccessfully.

You can access my boilerplate Node JS and Express JS code: node express boilerplate 2023.

You will find my entire Node JS starter template with a signal handler on my GitHub repository.

Let me walk you through the code and explain.

// When CTRL + C closes the app
server.on('close', () => {
  console.log('Express web server is closing\n');
});

This part of the code sets up an event listener for the close event on the Express server.

When the server is about to close, this event is triggered. The callback function logs a message to the console, informing that the server is closing.

For best practices, in this callback, you would perform cleanup activities like closing database connections or clearing folders.

const closeServer = () => {
  return new Promise((resolve, reject) => {
    server.close((err) => {
      if (err) {
        reject(err);
      } else {
        resolve();
      }
    });
  });
};

The closeServer function returns a promise that triggers an Express close event.

The purpose of wrapping this task with a promise is to ensure the close event is done executing its callback before returning to the main thread of execution. In seeing what proceeds, we will better understand.

const CLOSE_SIGNAL = (
  process.env.NODE_ENV === environments.development ? SIGNAL.INTERRUPTION
  : process.env.NODE_ENV === environments.production ? SIGNAL.TERMINATION :
  SIGNAL.INTERRUPTION
);

In this code, I assign to the CLOSE_SIGNAL variable a signal type (SIGINT or SIGTERM) based upon the environment the Node JS instance is in (development or production).

SIGINT is associated with a development environment because this signal is typically sent when the user interrupts the process, like pressing Ctrl+C in the terminal. It's a standard way to stop a development server manually.

SIGTERM is associated with a production environment because it's often sent by process managers (PM2) or the operating system when it needs to shut down a process, for example, during system shutdowns or restarts.

process.on(CLOSE_SIGNAL, async () => {
  console.log(`\n\nReceived ${CLOSE_SIGNAL} signal...\n`);
  try {
    await closeServer();
    console.log("Closed server.\n")
    process.exit(0);
  } catch (err) {
    console.error('Error while closing the server and disconnecting from sequelize:', err);
    process.exit(1);
  }
});

This part of the code adds a listener for the termination signal (SIGINT or SIGTERM).

Upon receiving the signal, it attempts to close the server using the closeServer function. The fact that the function closeServer is awaited upon makes this main thread not proceed until the close event handler callback function (see code below) has completed its execution.

// When CTRL + C closes the app
server.on('close', () => {
  console.log('Express web server is closing\n');
});

If the await closeServer(); execution is successful, it exits the process with a status code of 0. A status 0 indicates that the exit was successful.

Whereas, if the await closeServer(); throws an error, it logs the error and exits with a status code of 1.

A status 1 indicates that the exit was a failure.

All this code is necessary for a graceful shutdown.

It ensures that when the application receives a termination signal, it performs the necessary cleanup and shuts down resources, activities and services before the process exits.

Consequently, it prevents abrupt termination and potential resource leaks or other issues.

How to instantiate a Node JS project

Read the following article to understand Node JS local and remote web servers and how to instantiate a local Node JS projet: Projet Node JS

Earnanswers Node JS project services

If you need a Node JS web application solution, Earnanswers can service your needs.

Earnanswers has the expertise to construct your app with the utmost simplicity and speed.

Notify us of your interest by submitting your email in the input box below, and we will promptly get back to you.

Our team is looking forward.

Mahdi Furry

Additional reads