CNode

如何判断一个文件是否存在?(在不适用fs.exists的情况下)

问答
Xxiaofuzi发布于11 年前最后回复11 年前7 回复18078 浏览0 收藏

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

查看回复

回复 (7)

C
coordcn#1·11 年前

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

Z
zyvas#2·11 年前

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

M
MiguelValentine#3·11 年前

fs.access

B
brickyang#4·11 年前

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

B
backsapce#5·11 年前

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

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

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

D
dogsmall#6·11 年前

fs.existsSync

L
lwsbox#7·11 年前

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.

参与回复
登录后即可参与回复。登录