The pattern is a race condition. Better: skip the check, do the operation, and handle the error.
This race is called time-of-check to time-of-use (TOCTOU). Between the check and the read, another process can delete, rename or replace the file. So the read can still fail, and you need error handling anyway. The check also adds a second system call. And existsSync blocks the event loop.
The better pattern:
- Call
readFileoropendirectly. - If it fails, check
err.code.'ENOENT'means the file is missing.EACCESmeans you don't have permission. - To create a file only if it doesn't exist yet, open it with the
wxflag. If the file exists, the call fails withEEXIST. This check and create happen as one atomic step, so no other process can get in between.
A standalone existence check is fine when you only want to report status and don't act on the file afterwards.
- Checking and then using a file is a TOCTOU race.
- The operation can fail anyway, so you must handle errors.
- Inspect
err.codefor values likeENOENTandEACCES. - Use the
wxflag to create a file only if it is missing, atomically.
Read more