// Step 1: Import the required 'http' module
const http = require('http');
// Step 2: Create an HTTP server using the 'createServer' method
const server = http.createServer((req, res) => {
// Step 3: Handle incoming HTTP requests
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello, World!\n');
});
// Step 4: Specify the port on which the server will listen for incoming requests
const port = 3000;
// Step 5: Start the server and listen on the specified port
server.listen(port, () => {
console.log(`Server running at http://localhost:${port}/`);
});
// Step 6: Event handler for server errors
server.on('error', (err) => {
console.error(`Server error: ${err}`);
});
// Step 7: Event handler for server close
server.on('close', () => {
console.log('Server closed.');
});
// Step 8: Gracefully shut down the server (optional)
process.on('SIGINT', () => {
server.close(() => {
console.log('Server gracefully shut down.');
process.exit(0);
});
});