You should not check for existence of a file before opening due to a race condition, see the below excerpt from the fs.exists()
docs.
Using fs.exists() to check for the existence 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 does not exist.
Node.js fs.exists()
Docs: Source
As the above states, you should just handle the error passed to the fs.open()
callback function. fs.open()
returning an Error via the err
argument to your callback with a code of ENOENT
won't cause an UncaughtException
which subsequently crashes your process (assuming you aren't handling this on the process object, process.on('UncaughtException', err => {})
).
You're probably throwing the Error in your code or using the word "throw" instead of "returns" when describing how the Error is passed back to your code. The above sample code wouldn't cause an UncaughtException
unless err.code !== 'ENOENT'
. If err.code !== 'ENOENT'
then that results in err
being thrown without a wrapping try/catch
block, that would cause your process to crash because of an UncaughtException