nodejs判断文件是否存在,如果不存在则创建并写入内容“hello sanshu.cn”
代码如下:
let fs = require('fs'); const path = 'd:/fstest1.txt'; fs.exists(path,(exist)=>{ if(exist){ console.log('已经存在'); }else{ fs.writeFile(path,'hello sanshu.cn',(error)=>{ if(error){ console.log('写入失败'); return; }else{ console.log('成功'); } }); } })
运行结果:
打开创建后的文件
当再次运行脚本时,会提示文件已经存在: