Why using fstat is not recommended

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.

+5
source share
1 answer

I believe that it should be clear here that both fs.stat and fs.access not recommended for the specific case of checking the availability of a file before opening it. As already mentioned in the question, this can cause race conditions. For this reason, the exists() and existsSync() functions were deprecated (around version 4) (and several others related to the API): they were often used for this purpose.

When you try to open a file, the operation will raise an error if the file is not available. Therefore, such checks should be considered here. Otherwise, there is more than one reasonable way to check if a file exists .

Also note that from version 6.8.0 existsSync() not updated! See discussion and 6.8.0 changelog . The rules are the same as above: use it if you are not going to open the file later.

+3
source

Source: https://habr.com/ru/post/1258817/


All Articles