node.js - check if file exists before creating temp file

守給你的承諾、 提交于 2020-01-05 09:33:55

问题


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

  1. Generate a file name based on pid, time, and random chars
  2. Check if file exists
    • if yes: return to step 1 and repeat
    • if not: create the file and return it

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

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?


回答1:


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.

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.



来源:https://stackoverflow.com/questions/27528034/node-js-check-if-file-exists-before-creating-temp-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!