【发布时间】:2014-03-15 22:16:30
【问题描述】:
我对似乎节点 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() 之间删除文件。 只需打开文件并在错误不存在时处理它。"
我明白,所以在我选择“错误方式”之前 -
检查文件是否存在的常用方法是什么(如果是,打开它)/(也许最快的答案也是如此) - 使用节点 fs() ?
我的程序中的逻辑很简单 -
if (file does not exist) { continue the tasks to create it; }
else { read it and respond with it; }
非常感谢
【问题讨论】:
标签: javascript node.js