Hiprup

Is Node.js single-threaded? If so, how does it handle concurrency?

Yes, Node.js runs JavaScript on a single main thread, but it handles concurrency efficiently through its event loop and non-blocking I/O model.

Event loop — continuously picks up completed I/O events and runs their callbacks on the main thread.

  • Non-blocking I/O — I/O operations (network, DB, files) are delegated to the OS or libuv, so the main thread never waits.

  • libuv thread pool — handles blocking operations like filesystem, DNS, and crypto in background threads (default size: 4).

  • Reactor Pattern — Node reacts to events instead of blocking on them, allowing thousands of concurrent connections on one thread.


Key terms: event loop, non-blocking I/O, libuv, thread pool, worker threads, Reactor Pattern.

const fs = require('fs');

console.log('Start');

fs.readFile('example.txt', 'utf8', (err, data) => {
  if (err) throw err;
  console.log('File read complete');
});

console.log('End');
// Output: Start, End, File read complete

This demonstrates non-blocking behavior. The readFile call is asynchronous, so Node.js does not wait for it to finish.

It logs 'Start', initiates the file read, logs 'End', and only later when the file read completes does it log 'File read complete'. This is how a single thread handles concurrency without blocking.

This is one of the most frequently asked Node.js questions. Clarify that the JavaScript execution is single-threaded but libuv uses a thread pool internally.

Mentioning worker threads and the cluster module as solutions for CPU-bound work shows deeper understanding.

Is Node.js single-threaded? If so, how does it handle concurrency? | Hiprup