node.js-在创建临时文件之前检查文件是否存在
我想在node.js中创建一个临时文件/目录。为此,我尝试一种简单的算法:
I want to create a temporary file/directory in node.js. To do this, I'm attempting a simple algorithm:
- 根据pid,时间和随机字符生成文件名
- 检查文件是否存在
- 如果是:返回步骤1并重复
- 如果不存在:创建文件并返回
这是问题所在:node.js文档 fs.exists
明确地指出不应使用 fs.exists
,而是使用应该只使用 fs.open
并捕获潜在的错误:
http://nodejs.org/docs/latest/api/fs.html#fs_fs_exists_path_callback
Here's the problem: The node.js documentation for fs.exists
explicitly states that fs.exists
should not be used, and instead one should just use fs.open
and catch a potential error:
http://nodejs.org/docs/latest/api/fs.html#fs_fs_exists_path_callback
在我的在这种情况下,我不希望打开该文件(如果存在),而是严格尝试查找一个还不存在的文件名。有什么办法可以解决我不使用 fs.exists
的问题吗?或者,如果我确实使用 fs.exists
,我是否担心此方法将来会被弃用?
In my case, I am not interested in opening the file if it exists, I am strictly trying to find a filename that does not yet exist. Is there a way I can go about this that does not use fs.exists
? Alternatively, if I do use fs.exists
, should I be worried that this method will become deprecated in the future?
使用 fs.open
带有'wx'
标志,以便在文件不存在时创建该文件,并如果错误已经存在,则返回错误。
Use fs.open
with the 'wx'
flags instead so that you'll create the file if it doesn't exist, and return an error if it already exists.
这样,您可以(尽管很短)消除在 fs.exists之间创建文件的可能性。 / code>检查并通过
fs.open
调用来创建文件。
That way you eliminate the (albeit minute) possibility that the file is created between a fs.exists
check and an fs.open
call to create the file.