Node.js stream là gì?
Node.js stream là gì?
Stream là cách xử lý dữ liệu theo từng phần (chunk) thay vì nạp toàn bộ vào bộ nhớ. Đọc file 5GB bằng readFile cần 5GB RAM; dùng stream chỉ cần vài chục KB bộ đệm tại một thời điểm, và có thể bắt đầu xử lý ngay khi chunk đầu tiên tới.
| Loại | Ý nghĩa | Ví dụ |
|---|---|---|
| Readable | Nguồn dữ liệu | fs.createReadStream, http.IncomingMessage (req), process.stdin |
| Writable | Đích ghi | fs.createWriteStream, http.ServerResponse (res), process.stdout |
| Duplex | Vừa đọc vừa ghi, hai chiều độc lập | net.Socket |
| Transform | Duplex biến đổi dữ liệu đi qua | zlib.createGzip(), crypto.createCipheriv() |
import { createReadStream, createWriteStream } from 'node:fs';
import { createGzip } from 'node:zlib';
import { pipeline } from 'node:stream/promises';
import http from 'node:http';
// Nén file: pipeline tự xử lý lỗi và đóng mọi stream
Đăng nhập để tham gia thảo luận cùng mọi người.
Chưa có bình luận nào
Hãy là người đầu tiên chia sẻ suy nghĩ của bạn.