node.js fs.exists() will be deprecated, what to use instead?
根据文档,将不推荐使用node.js fs.exists()。
他们的推理:
fs.exists() is an anachronism and exists only for historical reasons. There should almost never be a reason to use it in your own code.
In particular, checking if a file exists before opening it is an anti-pattern that leaves you vulnerable to race conditions: another process may remove the file between the calls to fs.exists() and fs.open(). Just open the file and handle the error when it's not there.
fs.exists() will be deprecated.
我目前正在移动文件之前使用它,因为fs.rename()似乎悄悄地覆盖了目标文件夹中具有相同名称的文件。
我的问题是;我应该怎么使用来防止fs.rename()覆盖目标文件夹中的文件?
我认为有一种我不知道的方法。否则,我看不到不赞成使用fs.exists()的原因。
按照建议使用fs.open()似乎是多余的,因为我不想打开文件。
根据@ jfriend00的请求进行编辑,以获取有关我在做什么的更多信息。
我正在开发一个Electron应用程序,用户可以在其中将文件分类到不同的目录中。它不是服务器软件,而是旨在每天在用户计算机上运行并处理其文档。到目前为止,这是用于移动文件的代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | function moveFile(destIndex){ var from = queue[currentQueueIndex].path; var to = destinations[destIndex].path + path.sep + path.basename(from); console.log("[i] Move file (from/to):"); console.log(from); console.log(to); //Check if file exists, if yes: give them the choice to cancel. fs.stat(to, function (err, stats) { if (err){ move(from, to); } else { var confirmed = confirm("File already exists, will overwrite."); if (confirmed) { move(from, to); } } }); next(); //Show the next file to the user } function move(from, to){ fs.rename(from, to, function (err) { if (err) throw err; console.log('[i] Move successful'); queue[currentQueueIndex].path = to; queue[currentQueueIndex].moved = true; }); } |
在第一条评论之后,即以fs.stat开头的部分,我检查了我将要使用fs.rename创建的文件是否已经存在。我想这取决于比赛条件,但是我找不到fs.rename以任何方式处理重复项。
由于此应用程序旨在用于"家庭计算",因此我认为在统计检查和重命名之间文件消失的情况不大可能发生。但是,我可以避免的潜在问题越多越好。
使用fs.existsSync()。
fs.existsSync()尚未被弃用。
https://nodejs.org/api/fs.html#fs_fs_existssync_path
fs.existsSync(path)
Added in: v0.1.21
path |
Synchronous version of fs.exists(). Returns true if the file exists, false otherwise.Note that fs.exists() is deprecated, but fs.existsSync() is not. (The callback >parameter to fs.exists() accepts parameters that are inconsistent with other >Node.js callbacks. fs.existsSync() does not use a callback.)
io.js文档提到使用
这是使用
1 2 3 4 5 6 7 8 9 10 | fs.stat('mycustomfile.csv', function (err, stats) { console.log(stats);//here we got all information of file in stats variable if (err) { return console.error(err); } fs.unlink('mycustomfile.csv',function(err){ if(err) return console.log(err); console.log('file deleted successfully'); }); }); |