Any Node. Js version. const fs = require("fs"); let path = "/path/to/something"; fs. lstat(path, (err, stats) => { if(err) return console.
To check the path in synchronous mode in fs module, we can use statSync() method. The fs. statSync(path) method returns the instance of fs. Stats which is assigned to variable stats.
existsSync() method is used to synchronously check if a file already exists in the given path or not. It returns a boolean value which indicates the presence of a file.
Why not just try opening the file ? fs.open('YourFile', 'a', function (err, fd) { ... })
anyway after a minute search try this :
var path = require('path');
path.exists('foo.txt', function(exists) {
if (exists) {
// do something
}
});
// or
if (path.existsSync('foo.txt')) {
// do something
}
For Node.js v0.12.x and higher
Both path.exists
and fs.exists
have been deprecated
*Edit:
Changed: else if(err.code == 'ENOENT')
to: else if(err.code === 'ENOENT')
Linter complains about the double equals not being the triple equals.
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);
}
});
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;
}
A easier way to do this synchronously.
if (fs.existsSync('/etc/file')) {
console.log('Found file');
}
The API doc says how existsSync
work:
Test whether or not the given path exists by checking with the file system.
Modern async/await way ( Node 12.8.x )
const fileExists = async path => !!(await fs.promises.stat(path).catch(e => false));
const main = async () => {
console.log(await fileExists('/path/myfile.txt'));
}
main();
We need to use fs.stat() or fs.access()
because fs.exists(path, callback)
now is deprecated
Another good way is fs-extra
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With