文件写入
文件写入
const fs = require("fs");
fs.writeFile("/tmp/test", "Hey there!", function (err) {
  if (err) {
    return console.log(err);
  }
  console.log("The file was saved!");
});
我们也可以直接使用 fs-extra 提供的 outputFile 函数来自动创建不存在的文件:
const fs = require("fs-extra");
const file = "/tmp/this/path/does/not/exist/file.txt";
fs.outputFile(file, "hello!", (err) => {
  console.log(err); // => null
  fs.readFile(file, "utf8", (err, data) => {
    if (err) return console.error(err);
    console.log(data); // => hello!
  });
});
// With Promises:
fs.outputFile(file, "hello!")
  .then(() => fs.readFile(file, "utf8"))
  .then((data) => {
    console.log(data); // => hello!
  })
  .catch((err) => {
    console.error(err);
  });
