James
James

Reputation: 87

Node js ENOENT file error handling

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);
})

Upvotes: 3

Views: 8192

Answers (3)

James
James

Reputation: 87

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
}

Upvotes: -1

peteb
peteb

Reputation: 19418

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

Upvotes: 4

Devan Buggay
Devan Buggay

Reputation: 2759

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

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

Upvotes: -2

Related Questions