3

I have a simple process that needs to open a file to read but if the file does not exist it should simply note/ignore the error and continue on.

I have tried many sources but cannot find on clear example of how to successfully check for the existance of a file with out the node process throwing an uncaughtexception ENOENT.

a simple example is:

fs.open('a.txt', 'r', function(err, fd) {
    if(err) {
        if(err.code === 'ENOENT' ){
            console.log("Does not exist");
            return;
        }

        throw err;
    }
    console.log(err.code);
})
James
  • 77
  • 3
  • 7

3 Answers3

4

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

Community
  • 1
  • 1
peteb
  • 18,552
  • 9
  • 50
  • 62
-1

I was also getting ENOENT for fs.exist and fs.existSync which made no sense. Oddly enough this was being caused by an unused variable (See below) once I removed this var the ENOENT went away, not sure why.

var params =     var params = {
    input: fs.createReadStream(msgfile),
    output: process.stdout,
    terminal: false
}
James
  • 77
  • 3
  • 7
  • Aside from the cut and paste issue and not reviewing the post i see where the ENOENT is coming from, don't know how i missed this. – James Jan 13 '18 at 14:24
-2

Try using fs.existsSync() before trying to open it.

https://nodejs.org/api/fs.html#fs_fs_existssync_path

Devan Buggay
  • 2,717
  • 4
  • 26
  • 35