2

I was going to use fs.access to see if a directory exists, then if it exists then write a file into that directory, if it's not then first create the directory and then write a file into it.

But in the docs it says this is not recommended `Using fs.access() to check for the accessibility of a file before calling fs.open(), fs.readFile() or fs.writeFile() is not recommended. Doing so introduces a race condition, since other processes may change the file's state between the two calls.

Instead, user code should open/read/write the file directly and handle the error raised if the file is not accessible.`

Is there a recommended way to check first then write ?

4

1 Answer 1

3

As the doc you just quoted says, the recommended approach is to simply use fs.open(), fs.readFile() or fs.writeFile() to attempt to load the file, and handle the error if it throws one.

3
  • if it ends up throwing the error, would it be wise to go right into making the directory then writing a file to it or is that bad practice? Should I show the user the error instead? @troyalford
    – georgej
    Commented Jan 24, 2017 at 4:32
  • 2
    I don't know your use case in order to determine that for you, unfortunately. In general, my advice would be: If your user is responsible for creating the file your program will read, prompt the user when you get the error. If your program is responsible for it - don't prompt the user, just create it. Commented Jan 24, 2017 at 4:33
  • 1
    gotcha, appreciate it
    – georgej
    Commented Jan 24, 2017 at 4:36

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.