What is Node.js & the Event Loop?

Node.js Fundamentals — What is Node.js & the Event Loop
Node.js Fundamentals
Course 1 · Chapter 1 · What is Node.js & the Event Loop

⚡ What is Node.js & the Event Loop

Node.js is a JavaScript runtime that lets you run JavaScript outside the browser — typically on servers and command-line tools. The magic behind Node.js is the event loop: a non-blocking, asynchronous execution model that makes it incredibly efficient at handling I/O operations. This chapter explains what Node.js is, why the event loop matters, and how asynchronous programming works.

🌐 What is Node.js?

Node.js is:

  • A JavaScript runtime — runs JavaScript code outside the browser
  • Built on Chrome's V8 engine — the same high-performance JavaScript engine that powers Google Chrome
  • Event-driven — built around an event loop for handling asynchronous operations
  • Non-blocking I/O — performs file/network operations without blocking execution
  • Single-threaded — your JavaScript runs on a single thread (though Node uses threads behind the scenes for I/O)

Browser JavaScript vs Node.js

Browser (Client-Side)
  • Runs in the user's browser
  • Accesses DOM, local storage
  • Handles user interactions
  • Limited file system access
  • Same-origin policy restrictions
Node.js (Server-Side)
  • Runs on servers/your machine
  • Full file system access
  • No DOM (no UI)
  • Database/network operations
  • Environment variables, secrets

🔄 The Event Loop: The Heart of Node.js

The event loop is Node.js's execution model. It allows Node.js to handle thousands of concurrent connections without creating a thread for each one.

// This code demonstrates the event loop in action console.log('1. Start'); setTimeout(() => { console.log('2. Timeout callback (async)'); }, 0); console.log('3. End'); // Output: // 1. Start // 3. End // 2. Timeout callback (async) // // Why? The setTimeout is async — it goes to the event loop queue // and the main code continues. After the call stack is empty, // the event loop processes the queued callback.

Call Stack

Where your synchronous code executes. Functions are pushed and popped as they run.

Event Loop

Checks if the call stack is empty, then processes callbacks from the queue.

Callback Queue

Where async callbacks (setTimeout, file reads, etc.) wait to be executed.

Non-Blocking

I/O operations don't pause execution — they're handled asynchronously.

⛔ Blocking vs Non-Blocking I/O

Two Approaches to File Reading

Blocking (❌ Don't do this)
const fs = require('fs'); // This BLOCKS execution const data = fs.readFileSync('file.txt', 'utf8'); console.log(data); // Waits for file to load // Other code is stuck waiting console.log('This runs after file loads');
Non-Blocking (✅ Do this)
const fs = require('fs'); // This DOESN'T block execution fs.readFile('file.txt', 'utf8', (err, data) => { console.log(data); // Callback when file loads }); // Other code runs immediately console.log('This runs right away');

📞 Callbacks: The Foundation of Async

A callback is a function passed to another function, to be called later when something happens:

function processFile(filename, callback) { // Read file asynchronously fs.readFile(filename, 'utf8', (err, data) => { if (err) { callback(err, null); // Error callback } else { callback(null, data); // Success callback } }); } // Usage: pass a callback processFile('data.txt', (err, data) => { if (err) console.error('Error:', err); else console.log('Data:', data); });
Note: Modern Node.js also supports Promises and async/await (which we'll cover in later chapters). But callbacks are fundamental to understanding how Node.js works.

▶️ Running Node.js

Your First Node.js Program

// hello.js console.log('Hello, Node.js!'); console.log('Node version:', process.version);

Run it:

$ node hello.js Hello, Node.js! Node version: v18.0.0

Interactive REPL: Type `node` to enter the interactive shell:

$ node > console.log('Hello!') Hello! > 2 + 2 4 > .exit

💻 Coding Challenges

Challenge 1: Understanding Execution Order

Write a Node.js script that logs numbers in different orders using synchronous code, setTimeout, and callbacks. Predict the output before running it.

Goal: Internalize how the event loop affects execution order.

→ Solution

Challenge 2: Blocking vs Non-Blocking

Create two versions of a program that reads a file: one using readFileSync (blocking) and one using readFile (non-blocking). Measure which is faster when reading multiple files.

Goal: See non-blocking I/O in action.

→ Solution

Challenge 3: Callback Pattern

Write a function that accepts a callback and calls it with data from a file. Use error-first callbacks (error as first param). Test both success and error paths.

Goal: Master the callback pattern used throughout Node.js.

→ Solution

💡 Node.js Philosophy: "No I/O blocking"

The golden rule of Node.js is: never block the event loop. Even a 1-second file read blocks everything. This is why non-blocking I/O is so important. Later chapters cover Promises and async/await, which make non-blocking code easier to read.

🎯 What's Next

Now that you understand what Node.js is and how the event loop works, we'll dive into Modules & npm — how to organize code and manage dependencies.