You should almost never actually use this. The same applies to fs.stat
.
Checking whether a file exists before doing something with it, can lead to race conditions in your application. Race conditions are extremely hard to debug and, depending on where they occur, they can lead to data loss or security holes. Using the synchronous versions will not fix this.
Generally, just do what you want to do, and handle the error if it doesn't work. This is much safer.
- If you want to check whether a file exists, before reading it: just try to open the file, and handle the
ENOENT
error when it doesn't exist. - If you want to make sure a file doesn't exist, before writing to it: open the file using an exclusive mode, eg.
wx
orax
, and handle the error when the file already exists.