Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is using fstat not recommended

I'm reading the manual for stat method here and it says:

Using fs.stat() to check for the existence of a file before calling fs.open(), fs.readFile() or fs.writeFile() is not recommended. Instead, user code should open/read/write the file directly and handle the error raised if the file is not available.

To check if a file exists without manipulating it afterwards, fs.access() is recommended.

So, I've got two questions:

  • Why using error handler is preferred way over fs.stat() to check for file existence?

  • And since I can use fs.access() to check for file existence, is using error handler mechanism still preferred way to ensure file is open?

I think I have found an answer to the second question:

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.

So probably fs.open() blocks file for other processes, while fs.stat() and fs.access() simply request information and other processes still can change/delete the file.

like image 437
Max Koretskyi Avatar asked Oct 26 '16 10:10

Max Koretskyi


1 Answers

I believe that what should be made clear here is that both fs.stat and fs.access are not recommended for the particular case of checking for the accessibility of a file before opening it. As well mentioned in the question, this can trigger race conditions. The functions exists() and existsSync() were deprecated (around version 4) for this reason (and a few others related to the API): they were often exploited for this purpose.

When seeking to open a file, the operation will already trigger an error if the file is inaccessible. Therefore, such checks should be handled here. Otherwise, there is more than one reasonable way to check if a file exists.

Also note that, as of version 6.8.0, existsSync() is undeprecated! See discussion and the 6.8.0 changelog. The same rules above apply: only use it if you do not intend to open the file afterwards.

like image 164
E_net4 stands with Ukraine Avatar answered Nov 01 '22 12:11

E_net4 stands with Ukraine