0
0
NodejsHow-ToBeginner · 3 min read

Is Node.js Single Threaded? Understanding Node.js Threading Model

Node.js runs JavaScript code on a single main thread using an event loop, making it single threaded for JavaScript execution. However, it uses additional threads in the background for tasks like file I/O and timers, so it is not strictly single threaded overall.
📐

Syntax

Node.js code runs inside a single main thread where JavaScript executes. The event loop manages asynchronous operations without blocking this thread.

Background threads handle system tasks like file reading or network requests, but JavaScript callbacks run on the main thread.

javascript
console.log('Start');
setTimeout(() => {
  console.log('Timeout finished');
}, 1000);
console.log('End');
Output
Start End Timeout finished
💻

Example

This example shows how Node.js runs code on a single thread but handles asynchronous tasks with the event loop.

javascript
console.log('Task 1');
setTimeout(() => {
  console.log('Async Task 2');
}, 0);
console.log('Task 3');
Output
Task 1 Task 3 Async Task 2
⚠️

Common Pitfalls

Many think Node.js can do multiple JavaScript tasks at the same time because it handles many requests concurrently. But JavaScript code itself runs on one thread, so CPU-heavy tasks block the event loop and slow everything.

To avoid blocking, use asynchronous APIs or worker threads for heavy computation.

javascript
/* Wrong: Blocking the event loop */
const start = Date.now();
while (Date.now() - start < 2000) {
  // Busy wait for 2 seconds
}
console.log('Done blocking');

/* Right: Using setTimeout to avoid blocking */
setTimeout(() => {
  console.log('Non-blocking');
}, 0);
Output
Done blocking Non-blocking
📊

Quick Reference

  • Main thread: Runs JavaScript code and event loop.
  • Event loop: Handles async callbacks without blocking.
  • Worker threads: Optional threads for CPU-heavy tasks.
  • Background threads: Used internally for I/O operations.

Key Takeaways

Node.js executes JavaScript on a single main thread using an event loop.
Asynchronous operations run in the background without blocking the main thread.
CPU-intensive tasks block the event loop and should be offloaded to worker threads.
Node.js uses additional threads internally for I/O and system tasks.
Understanding this model helps write efficient, non-blocking Node.js code.