How can I synchronously check, using node.js, if a file or directory exists?
-
74Synchronous operations are great for performing one-time file/directory operations before returning a module. For example, bootstrapping a configuration file. – jocull Jul 13 '16 at 19:17
-
2@PaulDraper *with a warm cache* isn't true in all cases. – mikemaccana Aug 17 '17 at 20:10
-
24No matter the performances, sometimes you just want to run it in a sync way for developer experience. For example, if you are using Node for a data processing script which should by design be blocking, in that case async `exists` just adds unnecessary callbacks. – Kunok Dec 18 '17 at 15:35
-
5Definitely +1 to Kunok's statement. In the rest of my code I only make code more complex when it's a bottleneck where the speed really matters. Why wouldn't I apply that principle to file reading? In many parts of many programs code simplicity/readability can be more important than execution speed. If it's a bottleneck area I'll use async methods to keep from stopping further code execution. Otherwise...sync is great. Don't blindly hate sync. – BryanGrezeszak Feb 17 '18 at 16:13
-
6Please... not "worth noting" because user asks explicitly how to do it synchronously. – jClark Mar 20 '18 at 18:34
18 Answers
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:
Current Answer
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
}
});
Historical Answers
Here are the historical answers in chronological order:
- Original answer from 2010
(stat
/statSync
orlstat
/lstatSync
) - Update September 2012
(exists
/existsSync
) - Update February 2015
(Noting impending deprecation ofexists
/existsSync
, so we're probably back tostat
/statSync
orlstat
/lstatSync
) - Update December 2015
(There's alsofs.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 forfs.stat
recommend usingfs.access
if you need to check for existence without opening) - Update December 2016
fs.exists()
is still deprecated butfs.existsSync()
is no longer deprecated. So you can safely use it now.
Original answer from 2010:
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.
Update September 2012
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
}
});
Update February 2015
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.
Update December 2015
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
}
});
Update December 2016
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.)

- 1,031,962
- 187
- 1,923
- 1,875
-
You can link to functions in the docs. In WebKit browsers (Safari in my case), right-click and select "Inspect Element" and then find in the HTML the "id" attribute for the function you want to point to. In this case: http://nodejs.org/docs/v0.2.5/api.html#fs-statsync-114 – ohmantics Dec 19 '10 at 21:02
-
@ohmantics: That's strange, I thought I did *exactly* that (right down to using a WebKit browser to find the element ID :-) ) and it didn't work. But your link works, so clearly not. (Even the anchor is the same as what found! Weird.) – T.J. Crowder Dec 19 '10 at 22:06
-
2@Jesse: `exists` doesn't tell you whether it's a directory, it could be a file or pipe or other file system object. And surely not "grossly" overcomplicated? `existsSync` would only replace the `lstatSync` call, the rest of it is just to show how it would work in a loop. (Not sure why I felt that was necessary, though.) – T.J. Crowder Sep 24 '11 at 08:39
-
@T.J.Crowder - Didn't mean to offend, just think that it's potentially dangerous to do this much blocking. I'd recommend at least wrapping this in `process.nextTick` calls if in a production environment. However, this is a perfectly reasonable solution if you're just scripting and it's absolutely necessary to test what kind of file it is. I just thought it was a little overkill for the OP's purposes. – Jesse Sep 26 '11 at 06:07
-
@Jesse: Well, I can't remember why I felt a looping example was necessary, but the OP did specifically say "synchronously", perhaps I figured the only good reason for a synchronous check was a loop... – T.J. Crowder Sep 26 '11 at 10:40
-
8path.exists and path.existsSync have both been deprecated in favor of fs.exists and fs.existsSync – Drew Sep 26 '12 at 01:22
-
-
-
2`fs.exists` and `fs.existsSync` will be deprecated. I created the [`is-there` library to replace them](https://github.com/IonicaBizau/node-is-there). @T.J.Crowder You can include it in your answer if you like. – Ionică Bizău Feb 27 '15 at 12:06
-
@IonicăBizău: Oh for crying out loud (at them, not you). Because there's no use case for checking whether something exists unless you want to open it. ***sigh*** – T.J. Crowder Feb 27 '15 at 12:39
-
@T.J.Crowder Yes... I really needed to check if a file exists or not, nothing more. That's why I created `is-there`. :-) – Ionică Bizău Feb 27 '15 at 13:05
-
When I saw they marked "exists" as deprecated, definitely a head slap. – Matthew Dean Apr 30 '15 at 22:52
-
16"Node folks think it's dumb to check whether something exists before opening it, which it is;" Why is it dumb to check if file exists? – Petr Hurtak Jun 20 '15 at 18:25
-
39@PetrHurtak: It isn't *always* (because there are lots of reasons for checking existance), but if you're going to *open* the file, it's best to just issue the `open` call and handle the exception or whatever if the file wasn't found. After all, the real world is chaotic: If you check first and it's there, that doesn't mean it'll still be there when you try to open it; if you check first and it isn't there, that doesn't mean it won't be there a moment later. Timing things like that seem like edge cases, but they come up *all the time*. So **if** you're going to open, no point in checking first. – T.J. Crowder Jun 20 '15 at 18:43
-
17And here I thought it was an anti-pattern to use errors for control flow: [link](http://programmers.stackexchange.com/questions/189222/are-exceptions-as-control-flow-considered-a-serious-antipattern-if-so-why) – argyle Jul 16 '15 at 21:42
-
@jeromeyers: Indeed it is. I'd be checking the existence of the file at some relevant time, *and* expecting that the open call may fail. But I don't control the NodeJS API... – T.J. Crowder Jul 17 '15 at 06:02
-
1@T.J.Crowder: So, I'll end up creating my own utility function, I think I'll call it "fsExists" ;) – argyle Jul 17 '15 at 13:48
-
4@jeromeyers: You could, but Ionică [has already done it for you](https://github.com/IonicaBizau/node-is-there) (see [comment above](http://stackoverflow.com/questions/4482686/check-synchronously-if-file-directory-exists-in-node-js/4482701?noredirect=1#comment45808351_4482701)). :-) – T.J. Crowder Jul 17 '15 at 13:53
-
3It's an anti-pattern to use errors for control flow and it leads to much more ulgy code, in my opinion. So they are deprecating a function, that others have to re-implement in own libraries? WTF ... – aurora Jan 01 '16 at 18:54
-
17Upvote for keeping the answer updated, superb. Wish more people would do this. – basickarl Jan 20 '16 at 12:42
-
4LOL. Im checking this post like couple years, and every time something new ))) – Eugene Dec 29 '16 at 18:08
-
Now the only question I have is, how do you get the path? By this I mean, I don't know if the file isn't there or i'm just getting the path wrong :O – Jamie Hutber Sep 01 '17 at 22:41
-
@T.J.Crowder please can you include the node minimal version for your last update answer? – stackdave Nov 24 '17 at 20:56
-
@stackdave: It's at the top of the answer: `existsSync`. Or am I misunderstanding? – T.J. Crowder Nov 25 '17 at 00:05
-
1These updates were a rollercoaster of emotion. Thank you for being so thorough. – HaulinOats Feb 02 '18 at 22:33
-
3
-
1@mikemaccana - Ah yes, good thing to add now that the API is stable! – T.J. Crowder Apr 17 '19 at 14:17
-
1"It's an anti-pattern to use errors for control flow" - normally this would be the case. But filesystem errors are handled using atomic operations coming from the Southbridge / CPU. Since many threads can access files, using errors means file-access is thread-safe and you get consistent results. Since this is OS level, this applies to all languages including 16mhz 286 cpu from the 80's. – TamusJRoyce Nov 30 '20 at 20:50
Looking at the source, there's a synchronous version of path.exists
- path.existsSync
. Looks like it got missed in the docs.
Update:
path.exists
and path.existsSync
are now deprecated. Please use .fs.exists
and fs.existsSync
Update 2016:
fs.exists
and been deprecated. Use fs.stat() or fs.access() instead.fs.existsSync
have also
Update 2019:
use fs.existsSync
. It's not deprecated.
https://nodejs.org/api/fs.html#fs_fs_existssync_path
-
1path.existsSync(p) is in the 0.4.10 docs http://nodejs.org/docs/v0.4.10/api/path.html – Paul Beusterien Aug 23 '11 at 22:31
-
26Actually, a more recent answer: path.existsSync is deprecated. It is now called `fs.existsSync`. – Olivier Lalonde Mar 01 '12 at 04:56
-
9Now the docs are saying fs.exists will be deprecated. http://nodejs.org/api/fs.html#fs_fs_existssync_path – Greg Hornby Feb 26 '15 at 06:12
-
I wrote a little library to replace the old `exists` function: [`is-there`](https://github.com/IonicaBizau/node-is-there) – Ionică Bizău Oct 19 '15 at 07:42
-
https://nodejs.org/api/fs.html#fs_fs_existssync_pathStability: 0 - Deprecated: Use fs.statSync() or fs.accessSync() instead. – Jan 01 '16 at 18:47
-
6currenct docs (version ~9) only labeled `fs.exists` as deprecated while `fs.existsSync` is not! – Kunok Dec 18 '17 at 15:38
-
Your 2016 update is just the opposite of the 2016 update in the accepted answer... Why? – bluenote10 Feb 13 '19 at 22:02
-
`fs.exists()` is deprecated, but `fs.existsSync()` is not, check the docs, you're reporting false information https://nodejs.org/api/fs.html#fs_fs_existssync_path – Francesco Casula Jun 13 '19 at 08:48
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.

- 2,156
- 21
- 18
-
4Nice, I added || isDirectory() to make it a file/folder checker. var stats = fs.statSync(filePath);return stats.isFile() || stats.isDirectory(); – bob Oct 09 '15 at 05:37
-
4If program doesn't have rights to access the file it still returns false even though file exists i.e. remove all rigts from file chmod ugo-rwx file.txt or in Windows Right Click ... Exception message: Exception fs.statSync (./f.txt): Error: EPERM: operation not permitted, stat 'X:\f.txt'. So this case isn't covered by upper code. – broadband Jan 26 '16 at 14:28
-
2Wow, JS is retarded sometimes. So sure, 97% of the time you will be using the file, but not having a simple `file.exists()` util for the 3% and instead forcing us to wrap this in a try catch? Get real... Bitch of the day. – expelledboy Oct 01 '16 at 10:35
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.

- 11,707
- 12
- 44
- 82
-
1
-
1
-
2For those that still need `exists` and `existsSync` I created [`is-there`](https://github.com/IonicaBizau/node-is-there). – Ionică Bizău Feb 27 '15 at 12:10
-
6This deprecation bugs me. Opening a file just to see if an error is thrown or not seems like a waste of resources when all that's needed is knowledge of the file's existence. – Josh Hansen Mar 07 '15 at 00:41
-
Or just open the file in creation mode and lock it from being used by other processes (which prevents it from being deleted until the process that locked it deletes it). – PSXGamerPro1 May 19 '21 at 14:54
I use below function to test if file exists. It catches also other exceptions. So in case there are rights issues e.g. chmod ugo-rwx filename
or in Windows
Right Click -> Properties -> Security -> Advanced -> Permission entries: empty list ..
function returns exception as it should. The file exists but we don't have rights to access it. It would be wrong to ignore this kinds of exceptions.
function fileExists(path) {
try {
return fs.statSync(path).isFile();
}
catch (e) {
if (e.code == 'ENOENT') { // no such file or directory. File really does not exist
console.log("File does not exist.");
return false;
}
console.log("Exception fs.statSync (" + path + "): " + e);
throw e; // something else went wrong, we don't have rights, ...
}
}
Exception output, nodejs errors documentation in case file doesn't exist:
{
[Error: ENOENT: no such file or directory, stat 'X:\\delsdfsdf.txt']
errno: -4058,
code: 'ENOENT',
syscall: 'stat',
path: 'X:\\delsdfsdf.txt'
}
Exception in case we don't have rights to the file, but exists:
{
[Error: EPERM: operation not permitted, stat 'X:\file.txt']
errno: -4048,
code: 'EPERM',
syscall: 'stat',
path: 'X:\\file.txt'
}

- 3,266
- 6
- 43
- 73
-
2Really like this, it's one of the few answers that's up to date since node has deprecated the last 37 ways of doing this – 1mike12 Jul 28 '16 at 05:41
-
Bah, you beat me to it. I could have saved some time if I had read this. – jgmjgm Nov 12 '17 at 19:59
-
const fs = require('fs');
check in the function like below,
if(fs.existsSync(<path_that_need_to_be_checked>)){
// enter the code to excecute after the folder is there.
}
else{
// Below code to create the folder, if its not there
fs.mkdir('<folder_name>', cb function);
}

- 228
- 3
- 8
fs.exists() is deprecated dont use it https://nodejs.org/api/fs.html#fs_fs_exists_path_callback
You could implement the core nodejs way used at this: https://github.com/nodejs/node-v0.x-archive/blob/master/lib/module.js#L86
function statPath(path) {
try {
return fs.statSync(path);
} catch (ex) {}
return false;
}
this will return the stats object then once you've got the stats object you could try
var exist = statPath('/path/to/your/file.js');
if(exist && exist.isFile()) {
// do something
}

- 2,666
- 1
- 25
- 22
Some answers here says that fs.exists
and fs.existsSync
are both deprecated. According to the docs this is no more true. Only fs.exists
is deprected now:
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.)
So you can safely use fs.existsSync() to synchronously check if a file exists.

- 1,878
- 4
- 22
- 33
The path
module does not provide a synchronous version of path.exists
so you have to trick around with the fs
module.
Fastest thing I can imagine is using fs.realpathSync
which will throw an error that you have to catch, so you need to make your own wrapper function with a try/catch.

- 46,459
- 16
- 98
- 112
You can use fs-extra (npm i fs-extra) and its fs.ensureFile or for a directory fs.ensureDir since fs.exists has been depricated and fs.access does not recommend that your edit that file after using it "Do not use fs.access() to check for the accessibility of a file before calling fs.open(), fs.readFile() or fs.writeFile(). Doing so introduces a race condition, since other processes may change the file's state between the two calls. Instead, user code should open/read/write the file directly and handle the error raised if the file is not accessible."

- 65
- 6
updated asnwer for those people 'correctly' pointing out it doesnt directly answer the question, more bring an alternative option.
Sync solution:
fs.existsSync('filePath')
also see docs here.
Returns true if the path exists, false otherwise.
Async Promise solution
In an async context you could just write the async version in sync method with using the await
keyword. You can simply turn the async callback method into an promise like this:
function fileExists(path){
return new Promise((resolve, fail) => fs.access(path, fs.constants.F_OK,
(err, result) => err ? fail(err) : resolve(result))
//F_OK checks if file is visible, is default does no need to be specified.
}
async function doSomething() {
var exists = await fileExists('filePath');
if(exists){
console.log('file exists');
}
}
the docs on access().

- 1
- 1

- 10,975
- 3
- 46
- 65
-
1
-
you should update your code to `function asyncFileExists(path) { //F_OK checks if file is visible, is default does no need to be specified. return new Promise(function (res, rej) { fs.access( path, fs.constants.F_OK, function (err) { err ? rej(err) : res(true); }, ); }); } ` – pery mimon Sep 25 '19 at 14:24
Using fileSystem (fs) tests will trigger error objects, which you then would need to wrap in a try/catch statement. Save yourself some effort, and use a feature introduce in the 0.4.x branch.
var path = require('path');
var dirs = ['one', 'two', 'three'];
dirs.map(function(dir) {
path.exists(dir, function(exists) {
var message = (exists) ? dir + ': is a directory' : dir + ': is not a directory';
console.log(message);
});
});
The documents on fs.stat()
says to use fs.access()
if you are not going to manipulate the file. It did not give a justification, might be faster or less memeory use?
I use node for linear automation, so I thought I share the function I use to test for file existence.
var fs = require("fs");
function exists(path){
//Remember file access time will slow your program.
try{
fs.accessSync(path);
} catch (err){
return false;
}
return true;
}

- 1,620
- 1
- 17
- 16
This is already answered, but if you like installing modules you can use dtfe
, which stands for
Does the file exist?
const dtfe = require('dtfe');
dtfe('package.json');
//=> true

- 8,525
- 5
- 47
- 53
-
Seems pointless when you could just import `existsSync` from the file system module–the fewer installed dependencies, the better. – asciidude Apr 10 '23 at 22:36
Here is a simple wrapper solution for this:
var fs = require('fs')
function getFileRealPath(s){
try {return fs.realpathSync(s);} catch(e){return false;}
}
Usage:
- Works for both directories and files
- If item exists, it returns the path to the file or directory
- If item does not exist, it returns false
Example:
var realPath,pathToCheck='<your_dir_or_file>'
if( (realPath=getFileRealPath(pathToCheck)) === false){
console.log('file/dir not found: '+pathToCheck);
} else {
console.log('file/dir exists: '+realPath);
}
Make sure you use === operator to test if return equals false. There is no logical reason that fs.realpathSync() would return false under proper working conditions so I think this should work 100%.
I would prefer to see a solution that does not does not generate an Error and resulting performance hit. From an API perspective, fs.exists() seems like the most elegant solution.

- 3,739
- 1
- 35
- 47
-
1@Dan, thanks. I removed the truncated text. I cannot recall what the note was. If it comes me I will add notes. – Timothy C. Quinn Oct 04 '15 at 14:41
-
1
From the answers it appears that there is no official API support for this (as in a direct and explicit check). Many of the answers say to use stat, however they are not strict. We can't assume for example that any error thrown by stat means that something doesn't exist.
Lets say we try it with something that doesn't exist:
$ node -e 'require("fs").stat("god",err=>console.log(err))'
{ Error: ENOENT: no such file or directory, stat 'god' errno: -2, code: 'ENOENT', syscall: 'stat', path: 'god' }
Lets try it with something that exists but that we don't have access to:
$ mkdir -p fsm/appendage && sudo chmod 0 fsm
$ node -e 'require("fs").stat("fsm/appendage",err=>console.log(err))'
{ Error: EACCES: permission denied, stat 'access/access' errno: -13, code: 'EACCES', syscall: 'stat', path: 'fsm/appendage' }
At the very least you'll want:
let dir_exists = async path => {
let stat;
try {
stat = await (new Promise(
(resolve, reject) => require('fs').stat(path,
(err, result) => err ? reject(err) : resolve(result))
));
}
catch(e) {
if(e.code === 'ENOENT') return false;
throw e;
}
if(!stat.isDirectory())
throw new Error('Not a directory.');
return true;
};
The question is not clear on if you actually want it to be syncronous or if you only want it to be written as though it is syncronous. This example uses await/async so that it is only written syncronously but runs asyncronously.
This means you have to call it as such at the top level:
(async () => {
try {
console.log(await dir_exists('god'));
console.log(await dir_exists('fsm/appendage'));
}
catch(e) {
console.log(e);
}
})();
An alternative is using .then and .catch on the promise returned from the async call if you need it further down.
If you want to check if something exists then it's a good practice to also ensure it's the right type of thing such as a directory or file. This is included in the example. If it's not allowed to be a symlink you must use lstat instead of stat as stat will automatically traverse links.
You can replace all of the async to sync code in here and use statSync instead. However expect that once async and await become universally supports the Sync calls will become redundant eventually to be depreciated (otherwise you would have to define them everywhere and up the chain just like with async making it really pointless).

- 4,240
- 1
- 25
- 18
-
1The original question does not specify that. I am also demonstrating how to do things unambiguously. Many answers might induce bugs due to lack of clarity. People often want to program things so it appears syncronous but don't necessarily want synchronous execution. statSync is not the same as the code I've demonstrated. Either accounts of what's actually desired are ambiguous, so you're only imposing your personal interpretations. If you find an answer you don't understand it might be better to simply ask in the comments or PM to work out what edits are needed. – jgmjgm Apr 05 '18 at 14:55
-
1If you want you can also steal my code sample, name it appropriately, put it on github, add it to npm and then the answer will only be one line/link :D. – jgmjgm Apr 05 '18 at 14:59
-
The code is short for sake of example but you're welcome to submit an edit suggestion to include && !isFile or a check for symlinks, etc (again though the question never explicitly states even that is what they want). As I have already pointed out my answer satisfies one interpretation of the question and does not do the same thing your one line proposal does. – jgmjgm Apr 10 '18 at 18:16
Chances are, if you want to know if a file exists, you plan to require it if it does.
function getFile(path){
try{
return require(path);
}catch(e){
return false;
}
}

- 117
- 1
- 7