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.