I read the manual for the stat method here and it says:
Using fs.stat () to check for a file before calling fs.open (), fs.readFile (), or fs.writeFile () is not recommended. Instead, the user code should open / read / write the file directly and handle the error that occurs if the file is not available.
To check if a file exists without subsequently manipulating it, fs.access () is recommended.
So, I have two questions:
Why is using an error handler preferable to fs.stat() to check for the existence of a file?
And since I can use fs.access() to check for the existence of a file, fs.access() error handler mechanism use another preferred way to ensure that the file is open?
I think I found the answer to the second question:
Using fs.access () to check file availability before calling fs.open (), fs.readFile (), or fs.writeFile () is not recommended. This leads to a race condition, as other processes may change the state of the file between two calls. Instead, the user code should open / read / write the file directly and handle the error if the file is not available.
Thus, it is possible that fs.open() blocks the file for other processes, and fs.stat() and fs.access() just asks for information, and other processes can still modify / delete the file.
source share