问题
I want to create a temporary file/directory in node.js. To do this, I'm attempting a simple algorithm:
- Generate a file name based on pid, time, and random chars
- 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