While working with Node.js, I used
fs module often. One function that I used frequently is
fs.exists() to check if the file is there before doing any processing. Today, I read through Node.js
fs documentation and found the following :
fs.exists() is an anachronism and exists only for historical reasons. There should almost never be a reason to use it in your own code.
In particular, checking if a file exists before opening it is an anti-pattern that leaves you vulnerable to race conditions: another process may remove the file between the calls to fs.exists() and fs.open(). Just open the file and handle the error when it’s not there.
It make sense. Suppose we want to get file stat using
fs.stat(), just call the function and see the error code. If the file is not exists, then you will have this error :
1 2 3 4
Node.js use POSIX codes to denote errors and its a long list. How do you translate the error ENOENT into friendly error message. Do you even know that ENOENT means
No such file or directory?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
We can have human friendly readable error