Check whether a path - or an array of paths - exists
npm install paths-exist -S
import { pathsExist } from "paths-exist";
pathsExist(<Array> pathsToCheck, <fs.constants> fsFlag)
Where
pathsToCheck
is an array of path strings you want to check.fsFlag
is an optional param where you can specify the expected file mode; F_OK is the default.
import { R_OK, W_OK, F_OK, pathsExist } from "paths-exist";
async () => {
await pathsExist();
// --> return null (because path param is empty)
await pathsExist(["readable/path", "second/readable/path"]);
// --> return true
await pathsExist(["readable/path", "second/readable/path"], F_OK);
// --> return true
await pathsExist(["readable/path", "second/readable/path"], R_OK);
// --> return true
await pathsExist(["unwritable/path", "other/unwritable/path"], W_OK);
// --> return false
await pathsExist(["real/path", "fake/path"]);
// --> return false
};
pathsExist(<String> pathToCheck, <fs.constants> fsFlag)
Where
pathToCheck
is a single path string you want to check.fsFlag
is an optional param where you can specify the expected file mode; F_OK is the default.
import { R_OK, W_OK, F_OK, pathsExist } from "paths-exist";
async () => {
await pathsExist();
// --> return null (because path param is empty)
await pathsExist("/real/file/path");
// --> return true
await pathsExist("/real/file/path", F_OK);
// --> return true
await pathsExist("/fake/file/path", F_OK);
// --> return false
await pathsExist("/readable/path", R_OK);
// --> return true
await pathsExist("/writeable/path", W_OK);
// --> return true
};
Why
Sindre already has a small-bundled version for path-checking: path-exists. I wanted an API that was overloaded with the ability to check for an array of paths. While it would be quite simple to implement a factory, I ended up needing this functionality across a few different projects in a week and decided to abstract it.How
- File checks are done using
fs.access
with the default constantfs.constants.F_OK
. - You can overload this file constant with
F_OK
,W_OK
orR_OK
(as well as pairings eg.W_OK | R_OK
). - You can read more about the file constants here: File Access Constant
Name | Description |
---|---|
F_OK |
file is accessible |
R_OK |
file is readable |
W_OK |
file is writable |