← Back to Node.js Course | Chapter 1: Introduction | Lesson 2 of 7

How Node.js works

Node.js uses one main thread plus a helper system so it can wait for slow things like files and networks without freezing.

In this page:

  1. How Node.js works

How Node.js works

Node.js runs your JavaScript on a single thread, but hands slow I/O work (files, network, timers) to the operating system and a thread pool via libuv.

When the work finishes, a callback is queued and run on the main thread. This non-blocking model lets one process serve thousands of connections.

Note: CPU-heavy work blocks the single thread; move it to worker threads or another process.

Example: How Node.js works

javascript
console.log("1. start");

setTimeout(() => console.log("3. timer callback (after I/O style wait)"), 0);

console.log("2. end of script");

// Output:
// 1. start
// 2. end of script
// 3. timer callback (after I/O style wait)

⚠️ Run this in your own terminal or Node.js environment.

Related Topics
Common Mistakes
  1. Running long CPU loops on the main thread
  2. Assuming Node uses one thread for everything including I/O
  3. Blocking the event loop with synchronous file APIs in servers
Chapter Summary
  • JavaScript runs on one main thread
  • libuv handles async I/O
  • Callbacks run when work completes
  • Avoid blocking the main thread
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.