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?

user2221343
  • 614
  • 5
  • 16
  • With a filename format like that, I doubt you'd run into issues with duplicate filenames. – mscdex Dec 17 '14 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 – micnic Dec 17 '14 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 – user2221343 Dec 17 '14 at 15:01

1 Answers1

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.

JohnnyHK
  • 305,182
  • 66
  • 621
  • 471
  • 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 Dec 17 '14 at 14:52
  • @user2221343, from the message of the error, I guess, you can distinguish which error has occured – micnic Dec 17 '14 at 14:57
  • @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. – JohnnyHK Dec 17 '14 at 14:58
  • 1
    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) – user2221343 Dec 17 '14 at 15:11