In this lesson, you will learn how to catch system signals to stop your Node.js server without abruptly dropping active user connections.
The Problem: Abrupt Termination
When you stop a Node.js process (like when you press Ctrl+C or when a cloud orchestrator triggers a deployment), the process typically shuts down immediately. If your server is in the middle of sending a large file or processing a database transaction, that operation is cut off mid-stream. This leaves your clients with "Connection Reset" errors and potentially leaves your application state in an inconsistent mess.
Signal Handlers to the Rescue
Node.js processes can listen for system signals, specifically SIGTERM (the standard signal for termination) and SIGINT (sent by Ctrl+C). By listening for these, you can instruct your server to stop accepting new requests, while allowing existing ones to finish their work.
Implementing the Shutdown
To handle this, you need to call server.close() on your HTTP instance. This method tells Node.js to stop listening for new incoming connections, but it keeps the event loop alive until all current, active connections are finished.
const http = require('http');
const server = http.createServer((req, res) => {
res.end('Processing your request...');
});
server.listen(3000);
// Listen for termination signals
process.on('SIGTERM', () => {
console.log('Shutdown signal received. Closing server...');
server.close((err) => {
console.log('All connections closed. Exiting process.');
process.exit(err ? 1 : 0);
});
});
When server.close() is invoked, the server stays "up" just long enough for those persistent connections (which we learned about in the Keep-Alive lesson) to finalize. Once the last client disconnects, the callback runs, and your application exits cleanly.
This approach is vital for production environments where you want to deploy new code without interrupting the users currently browsing your site. By signaling that you are closing, you ensure the networking stack reaches a natural conclusion rather than a forced exit.
Key Takeaway: Use signal handlers to call server.close() so your application finishes active HTTP operations before exiting, preventing data loss and connection errors for your users.