写入文件内容writeFile()

writeFile(file, data[, options], callback)

  • file写入文件路径包含文件名称(没有文件则会创建文件)
  • data写入的内容(覆盖原本内容)
  • options写入文件内容的编码格式(默认utf8)
  • callback回调函数
    • err错误信息对象null ```javascript import { writeFile } from “fs”;

let path = “./index.txt”; let content = “Hello 沐颖汐”;

writeFile(path, content, err => { console.log(err); });

  1. <a name="dWT7f"></a>
  2. ### 判断写入文件是否成功
  3. ```javascript
  4. import { writeFile } from "fs";
  5. let path = "./index.txt";
  6. let content = "Hello 沐颖汐";
  7. writeFile(path, content, err => {
  8. if (err) {
  9. return console.log("写入文件失败:\n" + err.message);
  10. }
  11. console.log("写入文件成功\n");
  12. });