1导入fs模块
const fs = require('fs')
2,读取文件内容
fs.readFlie(path,'utf8',function(err,dataStr){ console.log(err) console.log('-----') console.log(dataStr) })
注:path为文件路径,成功err为null,失败err为错误对象,dataStr为undefined
3,powerShell输出:node 文件路径
优化版:
fs.readFlie('path','utf8',function(err,dataStr){ if(err){ return console.log('读取失败'+err.message) }
console.log('读取成功'+err.message)
})
4,写入内容
fs.writeFile('path','写入内容',function(err,dataStr){ if(err){ return console.log('写入失败'+err.message) } console.log('写入成功'+err.message) })
5,案例
const fs = require('fs')
fs.readFlie('path','utf8',function(err,dataStr){ if(err){ return console.log('读取失败'+err.message) }
//切割数组,替换字符串
const arrli = dataStr.split(' ')
const arrNew = []
arrli.forEach(item=>(
arrNew.push(itemm.replace('=',':'))
))
const nerStr = arrNew.join('\r\n')
console.log(newStr)
fs.writeFile('path',newStr,function(err){
if(err){
return console.log('写入失败'+err.message)
}
console.log('写入成功'+err.message)
})
})
标签:fs,console,log,err,写入,文件系统,导入,message,dataStr From: https://www.cnblogs.com/wencaiguagua/p/16804629.html