In this lesson, you will learn how to catch system signals to ensure your Node.js application shuts down gracefully instead of crashing abruptly.
Why Listen for Signals?
When you run a Node.js application, it stays alive as long as the Event Loop has tasks to process. Sometimes, an external authority—like a cloud provider or a terminal user—wants to stop your program. They do this by sending a Signal (a numeric interrupt) to your process.
The most common signal is SIGTERM (Signal Terminate). By default, if your app receives this, Node.js will kill the process instantly. This is dangerous because you might be in the middle of writing a file, saving to a database, or closing an active network connection. If the process dies mid-task, you risk data corruption.
Catching the Signal
To handle this, we use the process object, which acts as an EventEmitter. We can "listen" for the SIGTERM signal just like we listen for other events. When the signal arrives, we can perform our cleanup logic—like closing database pools or flushing logs—before manually exiting the process.
process.on('SIGTERM', () => {
console.log('Received SIGTERM. Starting graceful shutdown...');
// Perform cleanup tasks here:
// e.g., db.close(), server.close()
setTimeout(() => {
console.log('Cleanup finished. Exiting.');
process.exit(0); // 0 indicates success
}, 1000);
});
The "Graceful" Philosophy
When you catch a signal, you take responsibility for the process lifecycle. Instead of the system forcefully pulling the plug, you are given a moment to wrap up your "Close Callbacks" phase. By calling process.exit(0), you tell the operating system that you have finished your work cleanly and the process is ready to be terminated.
Remember, once you add a listener for SIGTERM, Node.js will no longer exit automatically when that signal is received. It is entirely up to you to call process.exit() once your cleanup code has finished its asynchronous work.
Key Takeaway: By listening for SIGTERM, you prevent data loss and corrupted states by ensuring your application completes its cleanup logic before the process terminates.