Node.js检查文件是否存在 [英] Node.js check if file exists
问题描述
如何检查文件的存在?
在模块fs
的文档中,对方法 fs.exists(path, callback)
一个>.但是,据我了解,它只检查目录的存在.我需要检查文件!
In the documentation for the module fs
there's a description of the method fs.exists(path, callback)
. But, as I understand, it checks for the existence of only directories. And I need to check the file!
这怎么办?
推荐答案
为什么不只是尝试打开文件? fs.open('YourFile', 'a', function (err, fd) { ... })
无论如何,经过一分钟的搜索,请尝试以下方法:
Why not just try opening the file ? fs.open('YourFile', 'a', function (err, fd) { ... })
anyway after a minute search try this :
var path = require('path');
path.exists('foo.txt', function(exists) {
if (exists) {
// do something
}
});
// or
if (path.existsSync('foo.txt')) {
// do something
}
对于Node.js v0.12.x及更高版本
path.exists
和fs.exists
均已弃用
Both path.exists
and fs.exists
have been deprecated
*
已更改:else if(err.code == 'ENOENT')
至:else if(err.code === 'ENOENT')
林特抱怨双重等于不是三次等于.
Linter complains about the double equals not being the triple equals.
使用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);
}
});
这篇关于Node.js检查文件是否存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!