nodejs判断文件是否存在、创建并写入

nodejs 文章 2020-02-15 18:46 1873 0 全屏看文

AI助手支持GPT4.0

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('成功');
            }
            
        });
    }
})


运行结果:

image.png


打开创建后的文件

image.png


当再次运行脚本时,会提示文件已经存在:

image.png


-EOF-

AI助手支持GPT4.0