1

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?

3
  • With a filename format like that, I doubt you'd run into issues with duplicate filenames. Commented Dec 17, 2014 at 14:41
  • I would also recommend you to add a suffix to the name like "_2" of the file rather than return to the step 1 Commented Dec 17, 2014 at 14:53
  • @micnic good point, that would prevent the (small) chance of randomly generating the same file name more than once. it's also worth modifying the algorithm a bit to limit the maximum number of attempts made :) for the sake of this question though, the above algorithm is sufficient Commented Dec 17, 2014 at 15:01

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

4 Comments

That's great! One question though, how can I tell that an error from fs.open is because the file already exists, versus some other IO error (too many files open, etc...)?
@user2221343, from the message of the error, I guess, you can distinguish which error has occured
@user2221343 The error object that you get will contain the details you need to differentiate the specific error. Create a little test to see what you get in that case; it's likely an EEXIST error.
Just tested this; you're correct, it is possible to check if (err.code === 'EEXIST') here to determine that the file already exists. The same is possible with fs.mkdir (for creating temp directories)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.