Sobes.tech
Middle

Is Node.js single-threaded or not? How many threads can a Node.js executable file occupy and why? What is libuv and how is it related to the event loop?

sobes.tech AI

Answer from AI

Node.js is fundamentally single-threaded, meaning JavaScript code executes in a single main thread. However, the Node.js executable can utilize multiple threads thanks to the internal libuv mechanism, which manages a thread pool for executing asynchronous operations such as file input/output, DNS queries, and other tasks not directly supported by the event loop.

By default, libuv creates a pool of 4 worker threads, but this number can be changed via the environment variable UV_THREADPOOL_SIZE (maximum 128).

The event loop is a cycle that handles asynchronous operations and callbacks in the main thread. Libuv provides a low-level abstraction for working with the operating system, including managing this event loop and the thread pool for executing heavy or blocking tasks outside the main thread.

Example: when you call an asynchronous file read, libuv places this operation in the thread pool, while the event loop continues to process other events. When the read completes, the result is returned to the main thread via a callback.

const fs = require('fs');

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

console.log('File read initiated');

Here, the file reading occurs in the libuv thread pool, and the main thread is not blocked.