Nâng CaoNode.js iconNode.js

Streams trong Node.js là gì? Có những loại stream nào?

Stream xử lý data theo chunks — memory efficiency cực cao: đọc file 1GB chỉ tốn ~64KB RAM (default highWaterMark) thay vì 1GB.

  • Bốn loại: Readable (fs.createReadStream, HTTP req, process.stdin), Writable (fs.createWriteStream, HTTP res, process.stdout), Duplex (TCP socket — đọc và ghi độc lập), Transform (zlib.createGzip, crypto.createCipher — transform data flow through). pipeline() API (Node.js 10+) thay thế .pipe(): await pipeline(readStream, transformStream, writeStream) — tự cleanup và propagate errors (.pipe() không handle errors tốt).
  • Stream consumers với for await...of: for await (const chunk of readableStream) { process(chunk); } — ergonomic nhất.

Ví dụ thực: serve 1GB file với 0 timeout và thấp RAM: const src = fs.createReadStream(filePath); const gzip = zlib.createGzip(); await pipeline(src, gzip, res) — data chảy qua, không buffer toàn bộ.

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

Mở danh sách Node.js