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?
– Luiz Felipe
@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.
– Woss