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 ?

Naveed Ramzan
  • 3,565
  • 3
  • 25
  • 30
georgej
  • 3,041
  • 6
  • 24
  • 46
  • Check this, http://stackoverflow.com/questions/4482686/check-synchronously-if-file-directory-exists-in-node-js – Ishan Jain Jan 24 '17 at 04:20
  • http://stackoverflow.com/questions/4482686/check-synchronously-if-file-directory-exists-in-node-js – Asif Saeed Jan 24 '17 at 04:20
  • is there an async way to do it though? @IshanJain – georgej Jan 24 '17 at 04:24
  • @georgej fs.exists was depreciated, But as node docs say, You can use `fs.stat()`, `fs.access()` or as other people have said, You can simply open the directory and make sure `err.code != ENOENT` – Ishan Jain Jan 24 '17 at 04:50

1 Answers1

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.

Troy Alford
  • 26,660
  • 10
  • 64
  • 82
  • 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 Jan 24 '17 at 04: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. – Troy Alford Jan 24 '17 at 04:33
  • 1
    gotcha, appreciate it – georgej Jan 24 '17 at 04:36