How to check if file exists (asynchronous)

Asked

Viewed 2,620 times

1

In Node.JS, I use this method of fs to check if a file exists:

const fs = require('fs');

// [...]

if (fs.existsSync(path)) { /** Do stuff. */ }

The question is, how can I do the same thing, but in a way asynchronous?
Note: I use Node 8.10.0.

1 answer

0


Just use the method fs.access.

fs.access(path, fs.constants.F_OK, (err) => {
  console.log(err ? 'não existe' : 'existe');
});

But stick to the documentation:

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.

That is, if checking the existence of the file to later manipulate it, this form is not recommended, because it creates running conditions and other parts of the application can change the state of the file between calls.

The recommended is that you treat the exception when changing the file if it does not exist.

fs.open(path, 'r', (err, fd) => {
  if (err) {
    if (err.code === 'ENOENT') {
      console.error('Arquivo não existe');
      return;
    }

    throw err;
  }

  funcao_que_le_arquivo(fd);
});

Adapted example of the documentation itself

  • So how would it be a good practice to do it (following the documentation note)? Could you give an example in the above answer?

  • @Iffg would modify the file directly, without checking and treating the trigger exception if the file does not exist. There are several examples in the documentation cited.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.