How Node.js Handles Non-Blocking I/O Internally?

1. Definition

Non-blocking I/O means Node.js does not wait for operations like file reading, database calls, or API requests to complete. Instead, it continues executing other code and handles the result later.

2. Internal Components

  • Event Loop: Handles execution of tasks
  • libuv: Manages async operations and thread pool
  • Callback Queue: Stores completed tasks
  • Thread Pool: Executes heavy operations

3. How it Works (Step-by-Step)

  • Request comes to Node.js
  • Async task is offloaded to libuv
  • Thread pool processes the task
  • Result is placed in callback queue
  • Event loop picks it and executes callback

4. Example

const fs = require("fs");

console.log("Start");

fs.readFile("file.txt", "utf8", (err, data) => {
  console.log("File read completed");
});

console.log("End");

// Output:
// Start
// End
// File read completed

5. Why it is Fast

  • No waiting for I/O operations
  • Handles multiple requests simultaneously
  • Efficient use of CPU

6. Advantages

  • High performance
  • Scalable applications
  • Handles real-time data efficiently
  • Better resource utilization