gpt4 book ai didi

javascript - Node js - fs 文件存在 - 有点困惑

转载 作者:行者123 更新时间:2023-11-28 20:00:01 25 4
gpt4 key购买 nike

我对 Node fs() 检查文件是否存在的各种方法有点困惑。

我可以:( http://nodejs.org/api/fs.html#fs_fs_readfile_filename_options_callback )

fs.readFile('somefile.html', function (err, data) {
if (err) { /* it doesn't */ }
else { /* it does */ }
});

但是在错误下运行条件感觉很奇怪(预计文件有时不会存在)

然后是 fs.exists() ( http://nodejs.org/api/fs.html#fs_fs_exists_path_callback )

fs.exists('somefile.html', function (exists) {
if(exists) { /* it does */ }
else { /* it doesn't */ }
});

这感觉更符合逻辑,但后来我读到了这个:

“在打开文件之前检查文件是否存在是一种反模式,使您容易受到竞争条件的影响:另一个进程可能会在调用 fs.exists() 和 fs.open() 之间删除该文件。 只需打开文件并在文件不存在时处理错误。

我明白,所以在我选择“错误方式”之前 -

检查文件是否存在的常用方法是什么(如果是的话,请打开它)/(也许最快也是简洁的答案) - 使用 Node fs()

我的程序中的逻辑很简单 -

if (file does not exist) { continue the tasks to create it; } 
else { read it and respond with it; }

非常感谢

最佳答案

您可以使用 readFileSync 来做您想做的事情

var file = fs.readFileSync('somefile.html');
if (file) { do stuff }
else { error }

这个故事的寓意是你不需要做存在。这纯粹是检查文件是否存在。如果无法打开它,你可以运行readFile,它会出错。如果可以,它将返回数据。

关于javascript - Node js - fs 文件存在 - 有点困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21815173/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com