Stream xử lý data theo chunk nên cực tiết kiệm bộ nhớ: đọc file 1GB chỉ tốn ~64KB RAM (highWaterMark mặc định) 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 — biến đổi data khi chảy qua).
pipeline() (Node.js 10+) thay cho .pipe() vì tự cleanup và propagate error:
js
// phục vụ file 1GB, không buffer toàn bộ vào RAM
const src = fs.createReadStream(filePath)
const gzip = zlib.createGzip()
await pipeline(src, gzip, res)
// đọc từng chunk theo cách dễ chịu nhất
for await (const chunk of readableStream) {
handleChunk(chunk)
}Backpressure: khi Writable chậm hơn Readable, pipeline tự pause Readable để tránh OOM — đây chính là lý do không nên dùng .pipe() thủ công trong production.