SyntaxStudy
Sign Up
Node.js The Event Loop and Your First Server
Node.js Beginner 10 min read

The Event Loop and Your First Server

The Event Loop is the mechanism that allows Node.js to perform non-blocking I/O operations despite being single-threaded. It continuously checks the call stack and processes callbacks from the event queue.

Node's built-in http module lets you create a web server in just a few lines of code.

Example
// Event Loop phases (simplified):
// 1. timers      — setTimeout / setInterval callbacks
// 2. I/O         — completed I/O callbacks
// 3. poll        — retrieve new I/O events
// 4. check       — setImmediate callbacks
// 5. close       — close event callbacks

// ---- Your first HTTP server ----
const http = require('http');

const server = http.createServer((req, res) => {
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.end('Hello, World!\n');
});

const PORT = 3000;
server.listen(PORT, () => {
    console.log(`Server running at http://localhost:${PORT}/`);
});

// Visit http://localhost:3000 in your browser.
// Node.js handles each request asynchronously,
// so the server keeps listening for more requests.