How to use‘once’ to Handle SIGINT in Express
- We are using the process.once function to register a one-time event handler for SIGINT. This mainly makes sure that the server is closed properly.
- In the above approach, the callback is executed every time a SIGINT signal is received whereas, in this approach, the handler is executed only the first time as the SIGINT signal is received which prevents the subsequent executions and reduces the redundancy.
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, GFG!' ); }); const server = app.listen(port, () => { console.log(`Server is running on port ${port}`); }); let shuttingDown = false ; process.once( 'SIGINT' , () => { if (!shuttingDown) { shuttingDown = true ; 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