0
0
Node.jsframework~30 mins

Graceful shutdown handling in Node.js - Mini Project: Build & Apply

Choose your learning style9 modes available
Graceful Shutdown Handling in Node.js
📖 Scenario: You are building a simple Node.js server that needs to stop cleanly when the application is closed or restarted. This means it should finish any ongoing work and close resources properly before exiting.
🎯 Goal: Create a Node.js server that listens on port 3000 and handles shutdown signals gracefully by closing the server and logging a message before the program exits.
📋 What You'll Learn
Create a basic HTTP server using Node.js
Add a variable to track if the server is running
Implement a listener for shutdown signals like SIGINT
Close the server gracefully and log a shutdown message
💡 Why This Matters
🌍 Real World
Graceful shutdown is important for servers to close connections and free resources properly before stopping, avoiding data loss or corruption.
💼 Career
Many backend developer roles require knowledge of handling process signals and graceful shutdown to build reliable and maintainable server applications.
Progress0 / 4 steps
1
Create a basic HTTP server
Create a Node.js HTTP server using http.createServer that responds with 'Hello World' to any request. Make the server listen on port 3000.
Node.js
Need a hint?

Use http.createServer to create the server and server.listen(3000) to start it.

2
Add a running state variable
Add a variable called isRunning and set it to true to track if the server is currently running.
Node.js
Need a hint?

Declare let isRunning = true; after starting the server.

3
Listen for shutdown signals
Add a listener for the 'SIGINT' signal using process.on. Inside the listener, set isRunning to false and call server.close() to stop the server.
Node.js
Need a hint?

Use process.on('SIGINT', () => { ... }) to listen for the shutdown signal.

4
Log shutdown completion
Add a listener for the server's 'close' event. Inside it, log 'Server has shut down gracefully.' and call process.exit(0) to exit the program cleanly.
Node.js
Need a hint?

Use server.on('close', () => { ... }) to handle the server closing event.