Trung BìnhNode.js iconNode.js

fs module trong Node.js: fs.readFile vs fs.createReadStream khác nhau như thế nào?

fs.readFile() load toàn bộ file vào RAM trước khi callback — file 100MB chiếm ít nhất 100MB heap; 100 concurrent requests = 10GB RAM, dễ OOM crash. fs.createReadStream() đọc theo chunks (default highWaterMark 64KB) — file 100MB chỉ dùng ~64KB RAM bất kể bao nhiêu requests đồng thời.

  • Serve file thực tế: fs.createReadStream(filePath).pipe(res) stream thẳng đến TCP buffer không qua RAM. pipeline() API (Node 10+) tốt hơn pipe(): await pipeline(fs.createReadStream(path), res) — tự cleanup khi error, tránh memory leak khi client disconnect.
  • Backpressure tự động: pipe/pipeline dừng đọc file khi client chậm, tiếp tục khi TCP buffer drain.
  • Khi nào dùng readFile: config files < 1MB đọc lúc startup, JSON parse một lần.
  • Khi nào dùng createReadStream: file download, log streaming, CSV export, bất kỳ file > vài MB.

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

Mở danh sách Node.js