💎 When running an Express server, shutting it down gracefully ensures that ongoing requests complete and resources like database connections are properly cleaned up before the app exits.
💎 A graceful shutdown ensures that ongoing requests finish before the app exits.
Code Example
const express = require("express");
const app = express();
const PORT = 3000;
const server = app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
const shutdown = () => {
console.log("\nShutting down...");
server.close(() => {
console.log("Server closed. Cleanup complete.");
process.exit(0);
});
};
process.on("SIGINT", shutdown);
process.on("SIGTERM", shutdown);
🌟 Key Takeaways
✅ Listen for SIGINT
/ SIGTERM
signal 🚨 to trigger shutdown
✅ Ensures active requests complete 👍 before exiting
✅ Calls server.close()
to stop the server and release the port
This ensures a smooth exit without dropping connections abruptly! 🚀✨
Follow me to stay updated with my future posts:
Top comments (0)