Node.js - check if a file exists before creating a temporary file

I want to create a temporary file / directory in node.js. For this, I am trying to execute a simple algorithm:

  • Creating a file name based on pid, time and random chars
  • Check if file exists
    • if yes: go back to step 1 and repeat
    • if not: create file and return it

Here's the problem: The node.js documentation for fs.exists explicitly indicates that fs.exists should not be used, and instead 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 a file, if it exists, I am strictly trying to find the name of a file that does not exist yet. Is there a way that I can do this that fs.exists does not use? Alternatively, if I use fs.exists , should I be worried that this method will become obsolete in the future?

+1
file deprecated file-exists temp
source share
1 answer

Use fs.open with the 'wx' fs.open so that you create a file if it does not exist, and return if it already exists.

Thus, you remove (albeit a minute) the possibility of creating a file between the fs.exists tag and calling fs.open to create the file.

+3
source share

All Articles