So you can safely use fs. existsSync() to synchronously check if a file exists.
The simplest way to check if a certain directory exists in Node. js is by using the fs. existsSync() method. The existsSync() method returns true if the path exists, false otherwise.
Any Node. Js version. const fs = require("fs"); let path = "/path/to/something"; fs. lstat(path, (err, stats) => { if(err) return console.
The answer to this question has changed over the years. The current answer is here at the top, followed by the various answers over the years in chronological order:
You can use fs.existsSync()
:
const fs = require("fs"); // Or `import fs from "fs";` with ESM
if (fs.existsSync(path)) {
// Do something
}
It was deprecated for several years, but no longer is. From the docs:
Note that
fs.exists()
is deprecated, butfs.existsSync()
is not. (The callback parameter tofs.exists()
accepts parameters that are inconsistent with other Node.js callbacks.fs.existsSync()
does not use a callback.)
You've specifically asked for a synchronous check, but if you can use an asynchronous check instead (usually best with I/O), use fs.promises.access
if you're using async
functions or fs.access
(since exists
is deprecated) if not:
In an async
function:
try {
await fs.promises.access("somefile");
// The check succeeded
} catch (error) {
// The check failed
}
Or with a callback:
fs.access("somefile", error => {
if (!error) {
// The check succeeded
} else {
// The check failed
}
});
Here are the historical answers in chronological order:
stat
/statSync
or lstat
/lstatSync
)exists
/existsSync
)exists
/existsSync
, so we're probably back to stat
/statSync
or lstat
/lstatSync
)fs.access(path, fs.F_OK, function(){})
/ fs.accessSync(path, fs.F_OK)
, but note that if the file/directory doesn't exist, it's an error; docs for fs.stat
recommend using fs.access
if you need to check for existence without opening)fs.exists()
is still deprecated but fs.existsSync()
is no longer deprecated. So you can safely use it now.You can use statSync
or lstatSync
(docs link), which give you an fs.Stats
object. In general, if a synchronous version of a function is available, it will have the same name as the async version with Sync
at the end. So statSync
is the synchronous version of stat
; lstatSync
is the synchronous version of lstat
, etc.
lstatSync
tells you both whether something exists, and if so, whether it's a file or a directory (or in some file systems, a symbolic link, block device, character device, etc.), e.g. if you need to know if it exists and is a directory:
var fs = require('fs');
try {
// Query the entry
stats = fs.lstatSync('/the/path');
// Is it a directory?
if (stats.isDirectory()) {
// Yes it is
}
}
catch (e) {
// ...
}
...and similarly, if it's a file, there's isFile
; if it's a block device, there's isBlockDevice
, etc., etc. Note the try/catch
; it throws an error if the entry doesn't exist at all.
If you don't care what the entry is and only want to know whether it exists, you can use path.existsSync
(or with latest, fs.existsSync
) as noted by user618408:
var path = require('path');
if (path.existsSync("/the/path")) { // or fs.existsSync
// ...
}
It doesn't require a try/catch
but gives you no information about what the thing is, just that it's there. path.existsSync
was deprecated long ago.
Side note: You've expressly asked how to check synchronously, so I've used the xyzSync
versions of the functions above. But wherever possible, with I/O, it really is best to avoid synchronous calls. Calls into the I/O subsystem take significant time from a CPU's point of view. Note how easy it is to call lstat
rather than lstatSync
:
// Is it a directory?
lstat('/the/path', function(err, stats) {
if (!err && stats.isDirectory()) {
// Yes it is
}
});
But if you need the synchronous version, it's there.
The below answer from a couple of years ago is now a bit out of date. The current way is to use fs.existsSync
to do a synchronous check for file/directory existence (or of course fs.exists
for an asynchronous check), rather than the path
versions below.
Example:
var fs = require('fs');
if (fs.existsSync(path)) {
// Do something
}
// Or
fs.exists(path, function(exists) {
if (exists) {
// Do something
}
});
And here we are in 2015 and the Node docs now say that fs.existsSync
(and fs.exists
) "will be deprecated". (Because the Node folks think it's dumb to check whether something exists before opening it, which it is; but that's not the only reason for checking whether something exists!)
So we're probably back to the various stat
methods... Until/unless this changes yet again, of course.
Don't know how long it's been there, but there's also fs.access(path, fs.F_OK, ...)
/ fs.accessSync(path, fs.F_OK)
. And at least as of October 2016, the fs.stat
documentation recommends using fs.access
to do existence checks ("To check if a file exists without manipulating it afterwards, fs.access()
is recommended."). But note that the access not being available is considered an error, so this would probably be best if you're expecting the file to be accessible:
var fs = require('fs');
try {
fs.accessSync(path, fs.F_OK);
// Do something
} catch (e) {
// It isn't accessible
}
// Or
fs.access(path, fs.F_OK, function(err) {
if (!err) {
// Do something
} else {
// It isn't accessible
}
});
You can use fs.existsSync()
:
if (fs.existsSync(path)) {
// Do something
}
It was deprecated for several years, but no longer is. From the docs:
Note that
fs.exists()
is deprecated, butfs.existsSync()
is not. (The callback parameter tofs.exists()
accepts parameters that are inconsistent with other Node.js callbacks.fs.existsSync()
does not use a callback.)
Looking at the source, there's a synchronous version of path.exists
- path.existsSync
. Looks like it got missed in the docs.
path.exists
and path.existsSync
are now deprecated. Please use .fs.exists
and fs.existsSync
fs.exists
and been deprecated. Use fs.stat() or fs.access() instead.fs.existsSync
have also
use fs.existsSync
. It's not deprecated.
https://nodejs.org/api/fs.html#fs_fs_existssync_path
Using the currently recommended (as of 2015) APIs (per the Node docs), this is what I do:
var fs = require('fs');
function fileExists(filePath)
{
try
{
return fs.statSync(filePath).isFile();
}
catch (err)
{
return false;
}
}
In response to the EPERM issue raised by @broadband in the comments, that brings up a good point. fileExists() is probably not a good way to think about this in many cases, because fileExists() can't really promise a boolean return. You may be able to determine definitively that the file exists or doesn't exist, but you may also get a permissions error. The permissions error doesn't necessarily imply that the file exists, because you could lack permission to the directory containing the file on which you are checking. And of course there is the chance you could encounter some other error in checking for file existence.
So my code above is really doesFileExistAndDoIHaveAccessToIt(), but your question might be doesFileNotExistAndCouldICreateIt(), which would be completely different logic (that would need to account for an EPERM error, among other things).
While the fs.existsSync answer addresses the question asked here directly, that is often not going to be what you want (you don't just want to know if "something" exists at a path, you probably care about whether the "thing" that exists is a file or a directory).
The bottom line is that if you're checking to see if a file exists, you are probably doing that because you intend to take some action based on the result, and that logic (the check and/or subsequent action) should accommodate the idea that a thing found at that path may be a file or a directory, and that you may encounter EPERM or other errors in the process of checking.
Another Update
Needing an answer to this question myself I looked up the node docs, seems you should not be using fs.exists, instead use fs.open and use outputted error to detect if a file does not exist:
from the docs:
fs.exists() is an anachronism and exists only for historical reasons. There should almost never be a reason to use it in your own code.
In particular, checking if a file exists before opening it is an anti-pattern that leaves you vulnerable to race conditions: another process may remove the file between the calls to fs.exists() and fs.open(). Just open the file and handle the error when it's not there.
http://nodejs.org/api/fs.html#fs_fs_exists_path_callback
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