Pregunta

I mean, that's basically it. The nodejs docs state that exists is an anachonism, but I can't see how stat replaces it.

¿Fue útil?

Solución

The fs.stat() method doesn't actually replace fs.exists(), but you can find out if a file exists through an error code from other functions. You would directly use fs.stat() on a file, regardless of if the file existed or not. The same thing applies to fs.open(), fs.readFile(), etc.

fs.stat(file, function(err, stats) {
  // if err is ENOENT
});

The documentation suggests doing this because it removes the possibility of a race condition happening between a fs.exists() call and a actual file operation, where the file could be deleted in the time between asynchronous functions.


Here's an example of directly checking if a file exists, and if so, reading it. If a file doesn't exists, an err object's code property will contain the string ENOENT.

fs.readFile('/etc/passwd', function(err, data) {
  if (err.code == 'ENOENT') {
    // the file doesn't exist
  }

  // the file exists if there are no other errors
});
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top