0
0
Node.jsframework~30 mins

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

Choose your learning style9 modes available
Graceful shutdown on errors
📖 Scenario: You are building a simple Node.js server that needs to close resources properly when errors happen or when the server stops. This helps avoid problems like data loss or corrupted files.
🎯 Goal: Create a Node.js server that listens on port 3000 and shuts down gracefully when an error occurs or when the process receives a termination signal.
📋 What You'll Learn
Create a basic HTTP server using Node.js http module
Add an error event listener on the server to handle runtime errors
Add a function called gracefulShutdown to close the server and exit the process
Listen for SIGINT and SIGTERM signals to trigger graceful shutdown
💡 Why This Matters
🌍 Real World
Servers often need to close open connections and clean up resources before stopping. This prevents data loss and keeps systems stable.
💼 Career
Understanding graceful shutdown is important for backend developers and DevOps engineers to build reliable and maintainable server applications.
Progress0 / 4 steps
1
Create a basic HTTP server
Create a variable called http that requires the http module. Then create a server using http.createServer() that responds with 'Hello World' to every request. Finally, make the server listen on port 3000.
Node.js
Need a hint?

Use require('http') to import the module. Then use http.createServer to create the server. Use server.listen(3000) to start listening.

2
Add error event listener
Add an event listener on the server for the 'error' event. The listener should call a function named gracefulShutdown passing the error object.
Node.js
Need a hint?

Use server.on('error', (err) => { ... }) to listen for errors and call gracefulShutdown(err).

3
Create gracefulShutdown function
Create a function named gracefulShutdown that takes an error parameter. Inside, log the error message using console.error. Then close the server using server.close() and exit the process with code 1 inside the close callback.
Node.js
Need a hint?

Define function gracefulShutdown(error) { ... }. Use console.error to log the error message. Call server.close() with a callback that calls process.exit(1).

4
Handle termination signals
Add listeners for 'SIGINT' and 'SIGTERM' signals on process. Both listeners should call gracefulShutdown with a new Error object with the message 'Process terminated'.
Node.js
Need a hint?

Use process.on('SIGINT', () => { ... }) and process.on('SIGTERM', () => { ... }) to listen for termination signals. Call gracefulShutdown(new Error('Process terminated')) inside each.