1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
   | const fs = require("fs");
 
  const rs = fs.createReadStream("./file.txt", {   encoding: "utf8",                 }); let fileContent = ""; rs.on("data", (chunk) => {   fileContent += chunk; }); rs.on("open", (fd) => {   console.log("开始读取文件"); }); rs.on("end", () => {   console.log("文件已全部读取完毕,文件内容:", fileContent.toString()); }); rs.on("close", () => {   console.log("文件被关闭"); }); rs.on("error", (err) => {   console.log("读取文件失败", err); });
 
  const ws = fs.createWriteStream("./file.txt", {   encoding: "utf8",              });
  ws.write("hello world1");  ws.end("hello world2", () => {   console.log("文件写入完毕,写入数量:", ws.bytesWritten); });
  ws.on("open", () => {   console.log("文件被打开了"); }); ws.on("close", () => {   console.log("文件被关闭了"); }); ws.on("drain", () => {   console.log("写入数据超过highWaterMark,暂停写入");  }); ws.on("error", (err) => {   console.log("写入文件失败", err); });
  |