读取数据
1.引入fs模块
const fs = require('fs');
2.fs.readFile(path,[, pation],callback){
参数1 : 从哪里读取数据
参数2: 以什么编码格式读取数据 默认: null
参数3 : 回调 err, data
//fs.readFile('./data.txt','utf-8',function (err,data) { fs.readFile('./data1.txt',function (err,data) { // 如果有错误 if (err) { throw err; }
异步读取数据
const fs = require('fs');
try{
let data = fs.readFileSync('./data.txt','utf-8')
} catch(err) {
console.log('出错了')
}
写入数据
1.引入fs模块
const fs = require('fs');
2.fs.writeFile(file, data [,option], callback)
file参数1: 要把数据写入到哪里
data 参数2:数据类型
option 参数3:以什么编码格式写入到文件 默认值‘utf-8’
callback 参数4:回调函数 err
路径问题
console.log(__dirname); // 当前 js 文件所在的目录
__dirname : 当前 js 所在文件目录的绝对路径 + 相对路径 = 绝对路径
总结:拼接路径
path.join(__dirname,'./data.txt');