node.js-在创建临时文件之前检查文件是否存在 [英] node.js - check if file exists before creating temp file

查看:540
本文介绍了node.js-在创建临时文件之前检查文件是否存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在node.js中创建一个临时文件/目录。为此,我尝试一种简单的算法:

I want to create a temporary file/directory in node.js. To do this, I'm attempting a simple algorithm:


  1. 根据pid,时间和随机字符生成文件名

  2. 检查文件是否存在

    • 如果是:返回步骤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.

这篇关于node.js-在创建临时文件之前检查文件是否存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆