Comprehensive Guide to signal-exit for Handling Node.js Process Termination

Introduction to signal-exit

The signal-exit module in Node.js is a versatile utility that ensures proper handling of process termination. It listens for exit signals, such as SIGINT, SIGTERM, and other exit events to execute cleanup routines.

Installing signal-exit


npm install signal-exit

Basic Usage

Here is a simple usage of the signal-exit module:


const onExit = require('signal-exit');

onExit((code, signal) => {
  console.log(`Process exited with code: ${code}, signal: ${signal}`);
});

Advanced Usage

The signal-exit module allows advanced configurations, such as managing multiple callbacks and customizing the exit behavior:

Handling Multiple Callbacks


const onExit = require('signal-exit');

const callback1 = (code, signal) => {
  console.log('First callback code: ', code);
};

const callback2 = (code, signal) => {
  console.log('Second callback signal: ', signal);
};

onExit(callback1);
onExit(callback2);

Executing Cleanup Code


const onExit = require('signal-exit');

onExit(() => {
  console.log('Performing cleanup tasks...');
  // Custom cleanup code here
});

Example Application

In this example, we create a simple Node.js application that uses signal-exit to handle different exit scenarios:


const http = require('http');
const onExit = require('signal-exit');

const server = http.createServer((req, res) => {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World\n');
});

server.listen(3000, '127.0.0.1');
console.log('Server running at http://127.0.0.1:3000/');

onExit((code, signal) => {
  console.log(`Process is exiting with code: ${code} and signal: ${signal}`);
  server.close(() => {
    console.log('Server closed');
  });
});
  
// Simulate an exit event after 10 seconds
setTimeout(() => {
  process.kill(process.pid, 'SIGINT');
}, 10000);

With signal-exit, you can ensure that all necessary cleanup tasks are performed when your Node.js application exits, providing a robust way to handle termination signals and exit codes.

Hash: b3518748b6d3b6a800c4cd92fb1b55a15662c43798877325aa60a10478860851

Leave a Reply

Your email address will not be published. Required fields are marked *