Blog>
Snippets

Creating a Simple HTTP Server with Event Loop Demonstration

Set up a basic HTTP server and use console logs within various stages to demonstrate the event loop behavior.
const http = require('http');

// Set up the server
const server = http.createServer((req, res) => {
  console.log('Event: Incoming Request');
  res.writeHead(200, { 'Content-Type': 'text/plain' });
  res.end('Hello World\n');
});

server.listen(3000, '127.0.0.1', () => {
  console.log('Event: Server is running on port 3000');
});

// Demonstrate event loop
setInterval(() => console.log('Event: Event Loop Tick'), 1000);
This code demonstrates a simple HTTP server with event loop logging. The 'http' module is used to create an HTTP server. The server responds with 'Hello World' to all incoming requests. It listens on port 3000. Additionally, an interval is set up to log a message every second, showing the event loop is operational and not blocked by the server.