Skip to content

fs: add exists to fsPromises #53737

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions doc/api/fs.md
Original file line number Diff line number Diff line change
Expand Up @@ -1071,6 +1071,16 @@ including subdirectories and files.
When copying a directory to another directory, globs are not supported and
behavior is similar to `cp dir1/ dir2/`.

### `fsPromises.exists(path)`

<!-- YAML
added: REPLACEME
-->

* `path` {string|URL} The filepath to check.

Checks whether the given filepath exists.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That's not correct, the current implementation checks if the current process can access a file at that path.


### `fsPromises.glob(pattern[, options])`

<!-- YAML
Expand Down
10 changes: 10 additions & 0 deletions lib/internal/fs/promises.js
Original file line number Diff line number Diff line change
Expand Up @@ -1275,12 +1275,22 @@ async function* glob(pattern, options) {
yield* new Glob(pattern, options).glob();
}

async function exists(path) {
try {
await access(path, F_OK);
return true;
} catch {
return false;
}
}

module.exports = {
exports: {
access,
copyFile,
cp,
glob,
exists,
open,
opendir: promisify(opendir),
rename,
Expand Down
6 changes: 6 additions & 0 deletions test/parallel/test-fs-promises.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ const fs = require('fs');
const fsPromises = fs.promises;
const {
access,
exists,
chmod,
chown,
copyFile,
Expand Down Expand Up @@ -77,6 +78,11 @@ assert.strictEqual(
).then(common.mustCall());
}

{
exists(__filename).then(common.mustCall((exists) => assert.strictEqual(exists, true)));
exists('this file does not exist').then(common.mustCall((exists) => assert.strictEqual(exists, false)));
}

function verifyStatObject(stat) {
assert.strictEqual(typeof stat, 'object');
assert.strictEqual(typeof stat.dev, 'number');
Expand Down
Loading