fs模块

fs模块

读取数据

  1. 同步读取数据-> readFileSync

    参数(path,buffer)

const fs = require('fs');

const textIn = fs.readFileSync('./txt/input.txt','utf-8');
console.log(textIn)
  1. 异步读取数据 -> readFile

    参数(path,encoding fun, callback)

fs.readFile("./txt/start.txt", "utf-8", (err, data) => {
  console.log(data);
});
console.log("Will read file!");

​ 也可以连续调用

fs.readFile("./txt/start.txt", "utf-8", (err, data1) => {
  fs.readFile(`./txt/${data1}.txt`, "utf-8", (err, data2) => {
    console.log(data2);
  });
});
console.log("Will read file!");

输出数据

  1. 同步输出数据-> writeFileSync

    参数(path,content),这里执行两次的话上一次的文件会被覆盖

const textOut = `This is what we know about the avocado: ${textIn}
Create on ${Date.now()}`;

fs.writeFileSync("./txt/output.txt", textOut);
console.log("File written!");
  1. 异步输出数据 -> writeFile

    参数(path,content, encoding, callback)

fs.writeFile("./txt/final.txt", `${data1}\n${data2}`, "utf-8", (err) => {
      console.log("your file has been written!");
});
posted @ 2022-06-18 02:45  kihyun  阅读(42)  评论(0编辑  收藏  举报