Check whether a file or directory exists in Node.js
Use existsSync for a synchronous observation, or perform the intended filesystem operation directly and handle its actual error.
fs.existsSync(path) returns a boolean indicating whether the path exists as observed by the call. It works for files and directories, but does not prove that you can read the target or that it will still exist a moment later.
const fs = require('node:fs');
const target = '/path/to/file_or_directory';
console.log(fs.existsSync(target) ? 'Exists' : 'Not found or inaccessible');
This is a synchronous filesystem call. It may be reasonable during a small CLI's setup, but avoid unnecessary blocking work on a busy server's request path.
Use an asynchronous check when observation is the task
In an ES module:
import { access } from 'node:fs/promises';
import { constants } from 'node:fs';
try {
await access('/path/to/file', constants.F_OK);
console.log('The path exists');
} catch (error) {
console.error(`Could not access the path: ${error.code}`);
}
There is no fs.promises.exists(). The default access() mode is F_OK, which checks existence, not general read or write permission. R_OK and W_OK request other checks, subject to platform-specific semantics. A successful permission check still cannot guarantee the next operation succeeds.
Avoid checking before opening
Between an existence check and a read, another process can remove or replace the file. When reading is the goal, attempt the read and handle its error:
const fs = require('node:fs');
try {
const data = fs.readFileSync('settings.json', 'utf8');
console.log(data);
} catch (error) {
if (error.code === 'ENOENT') {
console.error('The file or part of its path does not exist');
} else {
throw error;
}
}
Use the promise-based readFile() in an asynchronous path. Distinguish missing files from permission failures or a path component that is not a directory; swallowing every error as “missing” hides useful evidence.
FAQ
Is existsSync deprecated? No. The deprecated API is the callback-based fs.exists(). The advice against “check, then open” concerns a race condition, not a blanket ban on observing whether a path exists.
How do I distinguish a file from a directory? Use stat() or statSync() and inspect isFile() or isDirectory(), handling errors. These follow symlinks; lstat() inspects the link itself. A dangling symlink can exist as a directory entry while existsSync() reports false for its missing target.
How do I ensure a directory exists? Call mkdir(path, { recursive: true }) directly. An existing directory is fine; a conflicting file or inadequate permissions can still cause failure.
References
Contact us
Join the community
to join the community
Try Guance
Start online and pay only for what you use.
Get startedChoose a Guance plan