Basic Signal Handling

  • We are performing the basic signal handling in this approach, where the application will mainly listen for the SIGINT signal when the Ctrl+C is been triggered in the terminal.
  • When the signal is received the Express server will get shut down properly by allowing the existing connections to finish the processing before exiting the process.

Example: Implementation of the above-discussed approach.

Javascript




//app.js
 
const express = require('express');
const app = express();
const port = 3000;
app.get('/', (req, res) => {
    res.send('Hello, World!');
});
const server = app.listen(port, () => {
    console.log(`Server is running on port ${port}`);
});
process.on('SIGINT', () => {
    console.log('Received SIGINT. Closing server...');
    server.close(() => {
        console.log('Server closed. Exiting process...');
        process.exit(0);
    });
});


Output:

How to properly handle SIGINT with Express.js?

Handling SIGINT in Express JS is mainly the process of shutting down the server. This SIGINT is mainly processed when we press the Ctrl + C in the terminal. For the proper shutting down of the server, we can handle this SIGINT using different approaches so that the proper cleanup of the task will be done and the server will get shut down properly.

In this article, we are going to properly handle SIGINT in Express with the given approaches.

Table of Content

  • Basic Signal Handling
  • Using ‘once’ to Handle SIGINT

Similar Reads

Prerequisites

Express JS Postman...

Steps to create Express application:

Step 1: In the first step, we will create the new folder by using the below command in the terminal....

Approach 1: Basic Signal Handling

We are performing the basic signal handling in this approach, where the application will mainly listen for the SIGINT signal when the Ctrl+C is been triggered in the terminal. When the signal is received the Express server will get shut down properly by allowing the existing connections to finish the processing before exiting the process....

Approach 2: Using ‘once’ to Handle SIGINT

...