Cơ BảnNode.js iconNode.js

Non-blocking I/O trong Node.js là gì? Tại sao quan trọng?

Non-blocking I/O cho phép Node.js xử lý hàng nghìn connections trên 1 thread — tránh readFileSync/JSON.parse(largeData)/vòng lặp nặng vì chúng block event loop và làm tất cả requests khác phải chờ.

  • Non-blocking I/O hoạt động nhờ libuv delegate I/O operations cho OS kernel hoặc thread pool: khi gọi fs.readFile(), Node.js đăng ký callback rồi trả control về event loop ngay lập tức, OS xử lý I/O ở background, khi xong thêm callback vào event queue để event loop xử lý.
  • So với blocking model Apache (thread-per-request): Apache cấp 1 thread/request, thread block khi chờ DB query — 1000 concurrent requests cần 1000 threads (~1GB RAM).
  • Node.js single-threaded xử lý 1000 requests trên 1 thread vì hầu hết thời gian chờ I/O là idle.
  • Throughput thực tế: Node.js thường đạt 10k-50k req/s cho I/O-heavy API, so với Apache ~1k-5k req/s.
  • Khi nào blocking xảy ra accidentaly: fs.readFileSync(), JSON.parse(largeData), vòng lặp tính toán nặng, crypto.pbkdf2Sync() — tất cả đều block event loop và làm tất cả requests khác phải chờ.
  • Solution: Worker Threads cho CPU-intensive, luôn dùng async variants.

Xem toàn bộ Node.js cùng filter theo level & chủ đề con.

Mở danh sách Node.js