Trung BìnhNode.js iconNode.js

Streams trong Node.js là gì? Tại sao cần dùng Streams thay vì đọc toàn bộ file?

Streams xử lý data theo từng phần nhỏ (chunks) thay vì load toàn bộ vào memory — rất quan trọng khi xử lý file lớn (CSV hàng GB, video).

Có 4 loại: Readable (đọc data, ví dụ fs.createReadStream), Writable (ghi data, ví dụ fs.createWriteStream), Duplex (vừa đọc vừa ghi, ví dụ TCP socket), Transform (biến đổi data trong quá trình truyền, ví dụ compression). Dùng .pipe() để nối streams: fs.createReadStream('big.csv').pipe(transform).pipe(res).

Nếu đọc file 2GB bằng fs.readFile sẽ cần 2GB RAM, nhưng Stream chỉ cần vài MB.

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

Mở danh sách Node.js