方法一:利用回调函数
const fs = require('fs')
const path = require('path')
const fileHelper = {
readFile:(path,cb)=>{
fs.readFile(path,{encoding:'utf8'},(err,data)=>{
if(!err){
cb(data)
}
})
},
writeFile:(path,content,cb)=>{
fs.writeFile(path,content,{encoding:'utf8'},(err)=>{
if(!err){
cb();
}
})
}
}
const testPath = path.join(__dirname,'SubscribeMsg.js')
fileHelper.readFile(testPath,(data)=>{
console.log(data)
})
const testwrite = path.join(__dirname,'hello.json')
fileHelper.writeFile(testwrite,'{ok:ok}',()=>{
console.log('写入成功')
})
注意:当嵌套过深的时候,十分不方便,可以用Promise改造
const fs = require('fs').promises
可以用一个支持Promises的fs对象
使用Promise进行文件读取写入操作
const fs = require('fs').promises
const path = require('path')
const fileHelper = {
readFile:(path)=>{
return fs.readFile(path,{encoding:'utf8'})
},
writeFile:(path,content)=>{
return fs.writeFile(path,content,{encoding:'utf8'})
}
}
const testPath = path.join(__dirname,'SubscribeMsg.js')
fileHelper.readFile(testPath).then((data)=>{
console.log(data)
})
const testwrite = path.join(__dirname,'hello.json')
fileHelper.writeFile(testwrite,'{ok:ok}').then(()=>{
console.log('ok')
})