区别
普通操作 readFile 与 writeFile 是一下将数据读取到内存中在进行操作,占用内存空间大
流式操作 对占用内存空间下 且速度比普通操作快,使用是大数据时使用
代码
const fs = require("fs");const path = require("path");//方式1 普通操作async function method1() {const from = path.resolve(__dirname, "./temp/abc.txt");const to = path.resolve(__dirname, "./temp/abc2.txt");console.time("方式1");const content = await fs.promises.readFile(from);await fs.promises.writeFile(to, content);console.timeEnd("方式1"); // 10m数据用啦90.549msconsole.log("复制完成");}//方式2 使用流async function method2() {const from = path.resolve(__dirname, "./temp/abc.txt");const to = path.resolve(__dirname, "./temp/abc2.txt");console.time("方式2");const rs = fs.createReadStream(from);const ws = fs.createWriteStream(to);rs.on("data", chunk => {//读到一部分数据const flag = ws.write(chunk);if (!flag) {//表示下一次写入,会造成背压rs.pause(); //暂停读取}});ws.on("drain", () => {//可以继续写了rs.resume();});rs.on("close", () => {//写完了ws.end(); //完毕写入流console.timeEnd("方式2"); // 10m数据使用啦36.088ms 操作大数据是建议使用流,速度快占用内存少console.log("复制完成");});}method2();
