3-Nodejs-使用fs文件系统模块
3-Nodejs-使用fs文件系统模块
fs 模块是Node.js官方提供的、用来操作文件的模块。它提供了一系列的方法和属性,用来满足用户对文件的操作需求。
fs.readFile() 读取文件
① 在当前目录新建 1.txt 文件
② 新增 2-readFile.js 文件并编写如下代码
// 导入 fs 模块
const fs = require('fs');
// 读取1.txt文件中的内容并打印
fs.readFile('./1.txt','utf8',function(err,dataStr){console.log('错误信息: '+err);console.log(dataStr);
})
③ 执行 2-readFile.js
fs.writeFile() 往文件写入内容
// 导入 fs 模块
const fs = require('fs');
// 往1.txt文件中写入指定字符串
fs.writeFile('./1.txt','随便写入一些内容','utf8',function(err){console.log('错误信息: '+err);
})