Node.js check if file exists
Edit:
Since node v10.0.0
we could use fs.promises.access(...)
Example async code that checks if file exists:
function checkFileExists(file) {
return fs.promises.access(file, fs.constants.F_OK)
.then(() => true)
.catch(() => false)
}
An alternative for stat might be using the new fs.access(...)
:
minified short promise function for checking:
s => new Promise(r=>fs.access(s, fs.constants.F_OK, e => r(!e)))
Sample usage:
let checkFileExists = s => new Promise(r=>fs.access(s, fs.constants.F_OK, e => r(!e)))
checkFileExists("Some File Location")
.then(bool => console.log(´file exists: ${bool}´))
expanded Promise way:
// returns a promise which resolves true if file exists:
function checkFileExists(filepath){
return new Promise((resolve, reject) => {
fs.access(filepath, fs.constants.F_OK, error => {
resolve(!error);
});
});
}
or if you wanna do it synchronously:
function checkFileExistsSync(filepath){
let flag = true;
try{
fs.accessSync(filepath, fs.constants.F_OK);
}catch(e){
flag = false;
}
return flag;
}
Consider opening the file directly, to avoid race conditions:
const fs = require('fs');
fs.open('foo.txt', 'r', function (err, fd) {
// ...
});
Using fs.existsSync
:
if (fs.existsSync('foo.txt')) {
// ...
}
Using fs.stat
:
fs.stat('foo.txt', function(err, stat) {
if (err == null) {
console.log('File exists');
} else if (err.code === 'ENOENT') {
// file does not exist
fs.writeFile('log.txt', 'Some log\n');
} else {
console.log('Some other error: ', err.code);
}
});
Deprecated:
fs.exists
is deprecated.
Using path.exists
:
const path = require('path');
path.exists('foo.txt', function(exists) {
if (exists) {
// ...
}
});
Using path.existsSync
:
if (path.existsSync('foo.txt')) {
// ...
}