Node.js检查存在文件

如何检查文件的存在?

在模块的文档中fs是对rhe方法fs.exists(path,callback)的描述。但是,据我所知,它检查只存在目录。我需要检查文件!

如何才能做到这一点?

解决方法

为什么不尝试打开文件? fs.open(‘YourFile’,’a’,function(err,fd){…}
反正一分钟后搜索试试这个:

var path = require('path'); 

path.exists('foo.txt',function(exists) { 
  if (exists) { 
    // do something 
  } 
}); 

// or 

if (path.existsSync('foo.txt')) { 
  // do something 
}

For Node.js v0.12.x

path.exists和fs.exists都已被弃用

使用fs.stat:

fs.stat('foo.txt',function(err,stat) {
    if(err == null) {
        console.log('File exists');
    } else if(err.code == 'ENOENT') {
        // file does not exist
        fs.writeFile('log.txt','Some log\n');
    } else {
        console.log('Some other error: ',err.code);
    }
});

相关文章

这篇文章主要介绍“基于nodejs的ssh2怎么实现自动化部署”的...
本文小编为大家详细介绍“nodejs怎么实现目录不存在自动创建...
这篇“如何把nodejs数据传到前端”文章的知识点大部分人都不...
本文小编为大家详细介绍“nodejs如何实现定时删除文件”,内...
这篇文章主要讲解了“nodejs安装模块卡住不动怎么解决”,文...
今天小编给大家分享一下如何检测nodejs有没有安装成功的相关...