Nearby lessons

20 of 21

🌐 Node.js – Network I/O, Libuv & Thread Pool

📌 What is Network I/O?

Network I/O in Node.js

In Node.js, I/O often refers to reading/writing files or network operations. Network operations either fetch external information into your application or send data from your application to external services.

🧵 Thread Pool & Async Methods

  • Libuv's thread pool helps execute some async methods, but not all.
  • Example: crypto.pbkdf2() uses the thread pool, whereas https.request() does not.

🔹 Result of Experiments

  • Although both crypto.pbkdf2() and https.request() are asynchronous, https.request() does not use the thread pool.
  • The behavior of https.request() is not affected by the number of CPU cores.

🔹 Network I/O Behavior

  • https.request() is a network I/O operation, not CPU-bound.
  • Libuv passes the work to the operating system kernel and periodically checks if the request has completed.

⚙️ Kernel in Operating System

  • The kernel is the central component of an operating system managing hardware and software operations.
  • It manages CPU, memory, devices, and system resources efficiently.
  • Acts as a bridge between software applications and hardware.
  • Handles running programs, accessing files, and connecting devices like printers and keyboards.

🔹 Network I/O Execution

  • Libuv passes network tasks to the OS kernel and checks completion without blocking the main thread.

📌 Summary – Libuv & Async Methods

  • Async methods in Node.js are handled by Libuv in 2 way:
  • 1. Native async mechanisms (preferred if available)
  • 2. Thread Pool (used for file I/O or CPU-intensive tasks if no native async support)
  • Libuv leverages OS-specific mechanisms: epoll (Linux), kqueue (MacOS), IOCP (Windows).
  • Using native async mechanisms ensures scalability as Node.js relies on the OS kernel instead of blocking the main thread.
Node.js Environment
RUNTIME ACTIVE
const crypto = require('crypto');

console.log("Start pbkdf2 experiments...");

const start = Date.now();
crypto.pbkdf2('password', 'salt', 100000, 64, 'sha512', () => {
  console.log('1:', Date.now() - start);
});

crypto.pbkdf2('password', 'salt', 100000, 64, 'sha512', () => {
  console.log('2:', Date.now() - start);
});
Terminal Output
Live Output Preview

🧠 Test Your Knowledge

4 Questions

Progress: 0 / 4
Keep Going!Event Loop in Node.js