Node.js check if file exists
Solution 1
Consider opening the file directly, to avoid race conditions:
const fs = require('fs');
fs.open('foo.txt', 'a', 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')) {
// ...
}
Solution 2
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;
}
Solution 3
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.
Solution 4
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
Solution 5
fs.exists(path, callback)
and fs.existsSync(path)
are deprecated now, see https://nodejs.org/api/fs.html#fs_fs_exists_path_callback and https://nodejs.org/api/fs.html#fs_fs_existssync_path.
To test the existence of a file synchronously one can use ie. fs.statSync(path)
. An fs.Stats
object will be returned if the file exists, see https://nodejs.org/api/fs.html#fs_class_fs_stats, otherwise an error is thrown which will be catched by the try / catch statement.
var fs = require('fs'),
path = '/path/to/my/file',
stats;
try {
stats = fs.statSync(path);
console.log("File exists.");
}
catch (e) {
console.log("File does not exist.");
}
Related videos on Youtube
RomanGor
Updated on February 17, 2022Comments
-
RomanGor over 2 years
How do i check the existence of a file?
In the documentation for the module
fs
there's a description of the methodfs.exists(path, callback)
. But, as I understand, it checks for the existence of only directories. And I need to check the file!How can this be done?
-
mb21 over 5 yearsAs of 2018, use
fs.access('file', err => err ? 'does not exist' : 'exists')
, see fs.access
-
-
RomanGor almost 11 yearsBut, as it turned out,
fs.exists
works too. I have had problems with permissions to the file. -
Arnaud Rinquin about 10 years
path.exists
actually is deprecated in favor offs.exists
-
Antrikshy over 9 yearsAnyone reading this now (Node.js v0.12.x) keep in mind that
fs.exists
andfs.existsSync
have also been deprecated. The best way to check file existence isfs.stat
, as demoed above. -
newprog about 9 yearsFrom Node js documentation, seems like the best way to go if you plan on opening the file after checking its existence, is to actually open it and handle the errors if it doesn't exists. Because your file could be removed between your exists check and the open function...
-
Andy almost 8 yearsBoth
fs.exists
andfs.existsSync
are deprecated according to the link you shared. -
Wtower almost 8 years
stats.isFile()
does not needfilename
. -
HaveF over 7 years@Imeurs but nodejs.org/api/fs.html#fs_fs_existssync_path say: Note that fs.exists() is deprecated, but fs.existsSync() is not.
-
shreddish about 7 yearsThe link you provided for fs.existsync clearly stats that it is NOT deprecated "Note that fs.exists() is deprecated, but fs.existsSync() is not. (The callback parameter to fs.exists() accepts parameters that are inconsistent with other Node.js callbacks. fs.existsSync() does not use a callback.)"
-
Dmitry Koroliov about 7 yearsthe first (from the top) answer, which mentioned where the
fs
variable comes from -
RyanZim over 6 years@Antrikshy
fs.existsSync
is no longer depricated, thoughfs.exists
still is. -
RyanZim over 6 years
fs.existsSync
was deprecated, but it no longer is. -
RyanZim over 6 yearsAt the time this answer was written, the info was correct; however,
fs.existsSync()
is no longer deprecated. -
AKMorris over 6 yearsUpvoted, this is definitely the most modern (2018) way to detect if a file exists in Node.js
-
Darpan about 6 years
existsSync
is not deprecated as per that doc, may be it was when you read it. -
Justin about 6 yearsYes this is the official recommended method to simply check if the file exists and manipulation afterwards is not expected. Otherwise use open/write/read and handle the error. nodejs.org/api/fs.html#fs_fs_stat_path_callback
-
samson about 6 yearsIn the documentation I find
fs.constants.F_OK
etc. Is it also possible to access them likefs.F_OK
? Weird. Also terse, which is nice. -
Philll_t almost 6 yearsIs this a promise or something? Doesn't seem to be executed asynchronously.
-
vipatron over 4 yearsAs @newprog said, the Nodejs documentation for fsPromises(fsp) indeed says that they are correct: Calling fsp.access() then calling fsp.open() can "introduce a race condition" in which "other processes may change the file's state between the two calls". "Instead, [...] open/read/write the file directly and handle the error [if] not accessible" Last part of linked section in docs
-
oldboy over 4 years@Antrikshy the
nodejs fs documentation
only saysfs.exists
is deprecated, but thatfs.existsSync
is fine ??? -
Jeremy Trpka about 4 yearsCould try doing it with
fs.promises.access(path, fs.constants.F_OK);
to simply make it a Promise instead of creating a Promise. -
antitoxic almost 4 yearsI have been using an even shorter version of this: does not exist:
!(await fs.stat(path).catch(() => false))
exists:!!(await fs.stat(path).catch(() => false))
-
Szczepan Hołyszewski over 3 yearsWhy not just try opening the file? Because that requires catching the error and distinguishing the error thrown as a result of file's nonexistence from any other possible error, while an
exists()
kind of API answers the question directly and can be used directly in a condition. -
Systems Rebooter about 3 yearsthank you! the first example is such an elegant way.
-
TOPKAT about 3 yearsThis code is so ugly compared to the simple
fs.exists
one...really wonder why they force us to use such alternatives :'-( -
ggorlen almost 3 yearsSynchronous is "easier", but it's also categorically worse because you block the whole process waiting for I/O and other tasks can't make progress. Embrace promises and asynchrony, which the app probably has to use anyway if it's nontrivial.
-
ggorlen almost 3 yearsA couple characters shorter and maybe easier to read:
const fileExists = path => fs.promises.stat(path).then(() => true, () => false);
-
Faither almost 3 yearsI'm sorry, but what does say that "
existsSync
" is deprecated exactly? -
Marius over 2 yearspls remove the 1st part of the answer, which works only for node < 0.12 (way too old)
-
Alexandre Andrade over 2 yearsAccording to the documentation: "fs.exists() is deprecated, but fs.existsSync() is not. The callback parameter to fs.exists() accepts parameters that are inconsistent with other Node.js callbacks. fs.existsSync() does not use a callback."
-
Константин Ван about 2 years
fs.constants.F_OK
, the flag indicating that the file is visible to the calling process, is not needed. It is the default. Justtry
–catch
await fs.access(path)
.