如何判断一个文件是否存在?(在不适用fs.exists的情况下)
发布于 8 年前 作者 xiaofuzi 16501 次浏览 来自 问答

直接使用fs.readFile或是fs.stat读取一个不存在的文件是会报错的。

7 回复

@qingfeng fs.exists已经被废弃了。

Use fs.stat() or fs.access() instead.

就是在 fs.stat 的报错里处理文件不存在的逻辑的

觉得fs.stat是比较好的选择吧,不过有些代码中为了兼容性(比如ghost blog中),可以这么写

try{
	fs.readFileSync(yourFileName);
}catch(e){
	//may you not have read permission or the file not exists
}

如果你文件比较小,这种方法也可以哈.

fs.existsSync

function fsExistsSync(path) { try{ fs.accessSync(path,fs.F_OK); }catch(e){ return false; } return true; }

官网是这么说的 fs.exists(path, callback) #Stability: 0 - Deprecated: Use fs.stat() or fs.access() instead.

fs.F_OK - File is visible to the calling process.** This is useful for determining if a file exists**, but says nothing about rwx permissions. Default if no mode is specified.

回到顶部