You have some options, let's see some.
Synchronous
If you prefer the synchronous way, there are a couple of methods in the API that you can use.
fs # accessSync
This method checks if a file is accessible. If it is not, that is, if it does not exist, it will throw an exception.
try {
if(fs.accessSync('/archivo.dat')) {
// existe
}
} catch (e) {
// no existe
}
You can create a wrapper for this:
function fileExists(path) {
try {
if(fs.accessSync('/archivo.dat')) {
return true;
}
} catch (e) {
return false;
}
}
fs # statSync
The previous solution is valid, but what would happen if there is a directory and a file with the same name? What would happen is that it would not throw any exception and if we forget this, it can cause us a headache when debugging.
The most viable solution would be statSync . This function lets you know if the file found is a directory or file.
function fileExists(path) {
try {
return fs.statSync(path).isFile();
} catch (e) {
return false;
}
}
Keep in mind that there may be errors when trying to see the availability of a file / directory; in this case it would be better to return false only if the error code is ENOENT
(error no entry): if(e.code === 'ENOENT')
and relaunch the error or handle it if another error occurred, such as permisos
.
If we wanted to adapt it to know if it is a directory, we will only have to change isFile
by isDirectory
.
Asynchronous
The asynchronous mode of the functions is very similar, the difference is that they receive a callback.
function fileExists(file, cb) {
fs.stat(file, (err, stats) => {
if (err) {
if (err.code === 'ENOENT') {
return cb(null, false);
} else { // en caso de otro error
return cb(err);
}
}
// devolvemos el resultado de 'isFile'.
return cb(null, stats.isFile());
});
}
And it would be used in the following way:
fileExists('/archivo.dat', (err, exists) => {
if(err) {
// manejar otro tipo de error
}
if(exists) {
// hacer algo si existe
} else {
// hacer algo si no existe
}
});
Or if you prefer the promises, you can use the module es6-promise :
function existsFile(path) {
return new Promise((resolve, reject) => {
fs.stat(file, (err, stats) => {
if (err) {
if (err.code === 'ENOENT') {
resolve(false);
} else { // en caso de otro error
reject(err);
}
}
// devolvemos el resultado de 'isFile'.
resolve(stats.isFile());
});
});
}
We would use it in the following way:
existsFile('/archivo.dat')
.then(exists => {
if(exists) {
} else {
}
})
.catch(err => {
// manejar error
});