跳到主要内容
CNode

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

问答
Xxiaofuzi发布于 11 年前最后回复 11 年前
7181230

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

查看回复

回复 (7)

L
lwsbox#711 年前

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.

D
dogsmall#611 年前

fs.existsSync

B
backsapce#511 年前

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

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

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

B
brickyang#411 年前

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

M
MiguelValentine#311 年前

fs.access

Z
zyvas#211 年前

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

C
coordcn#111 年前

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

参与回复

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