流操作
读取流
ts
import fs from "fs";
const readStream = fs.createReadStream("example/file.txt", "utf8");
readStream.on("data", (chunk) => {
console.log(chunk);
});
readStream.on("end", () => {
console.log("Read completed");
});
readStream.on("error", (error) => {
console.error(error);
});
写入流
ts
const writeStream = fs.createWriteStream("example/file.txt");
writeStream.on("open", () => {
writeStream.write("Hello World!\n");
writeStream.write("Another line!\n");
writeStream.end();
});
writeStream.on("finish", () => {
console.log("Write completed");
});
writeStream.on("error", (error) => {
console.error(error);
});
管道流
ts
import fs from "fs";
import zip from "zlib";
const readStream = fs.createReadStream("example/file.txt", "utf8");
const writeStream = fs.createWriteStream("example/file-copy.txt.gz");
const gzip = zip.createGzip();
readStream.pipe(gzip).pipe(writeStream);
writeStream.on("finish", () => {
console.log("Write completed");
});