我们在获取文件路径时,一般使用相对路径;可能能会出现路径拼接错误问题,因为提供了./或../开头的文件。并且移植性非常差,不利于后期维护。提供以下几种解决方式:
fs.writeFile('E:\\node.js\\writeFile\\c.txt','大家好,我系渣渣辉啊',(err)=>{
//1,如果文件写入成功,则err的值为null
//2,如果文件写入失败,则err的值为错误对象
console.log(err)
//对结果进行判断
if(err){
return console.log('文件写入失败1='+err)
}
console.log('文件写入成功1='+err)
})
fs.writeFile(__dirname+'/c.txt','大家好,我系渣渣辉啊222',(err)=>{
//1,如果文件写入成功,则err的值为null
//2,如果文件写入失败,则err的值为错误对象
console.log(err)
//对结果进行判断
if(err){
return console.log('文件写入失败='+err)
}
console.log('文件写入成功='+err)
})
const path=require('path')
//注意:../会抵消前面的路径
const pathStr=path.join('/a','/b/c','../','/d')
console.log('拼接=',pathStr) //\a\b\d
fs.writeFile(path.join(__dirname,'/c.txt'),'你好',(err)=>{
//对结果进行判断
if(err){
return console.log('文件写入失败2='+err)
}
console.log('文件写入成功2='+err)
})
const path=require('path')
/***
* path.basename 获取文件名
*/
const fpath='/a/b/c/index.html'
const fullName=path.basename(fpath)
console.log(fullName)//index.html
//通过第二个参数,去除后缀扩展名
const fullName2=path.basename(fpath,'.html')
console.log(fullName2)//index
/**
* path.extname() 获取文件扩展名
* */
const fpath2='/a/b/c/index.html'
console.log(path.extname(fpath2)) //.html