How to check if file exists (asynchronous)

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 an asynchronous way? Note: I use Node 8.10.0.     

asked by anonymous 21.03.2018 / 16:35

1 answer

0

Just use the fs.access method.

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

But beware of 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 you check the file for later manipulation, 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.

It is recommended that you handle the exception when you change 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 from the documentation itself

    
21.03.2018 / 16:52