【Node】File System

Node中fs是文件系统模块,提供了很多操作文件的方法,让我们有能力对文件进行写入 读取 删除等操作。fs模块提供了同步和异步的版本。 

写入文件案例(异步)

1 // 引入模块
2 const fs = require("fs")
3 
4 // 写入文件
5 fs.writeFile("./text.txt", "窗前明月光", (err)=> {
6     if (err) throw err;   
7     console.log("The file has been saved"); // 成功时显示
8 })

读取文件案例(异步)

const fs = require("fs");

fs.readFile("./hello.txt", "utf-8", (err, data)=> {
     if (err) throw err;
     console.log(data);
})   

我们用异步的方法分别写了 写入文件和读取文件的操作。

tips:writeFile 中第一个参数是文件路径 如果你要写入的文件是不存在的则会自动创建它
原文地址:https://www.cnblogs.com/qjuly/p/14487387.html