NodeJs: fs.stat() or fs.access() to check if a folder exists?
I guess the documentation suggest to use fs.access
to check if a file exists when there's no manipulation afterwards is because it's a lower level and simple API with a single purpose of checking file-access metadata (which include whether a file exists or not). A simpler API might be little bit better too in term of performance as it may just be a straightforward mapping to the underlying native code.(NOTE: I haven't do any benchmark, take my statement with grain of salt).
fs.stat
provide a higher level of abstraction compared to fs.access
. It returns information beyond file-access.
import {promises as fs} from "fs";
import * as oldfs from "fs";
(async function() {
// fs.stat has higher level abstraction
const stat = await fs.stat(__dirname);
console.log(stat.isDirectory());
console.log(stat.isFile());
console.log(stat.ctime);
console.log(stat.size);
try {
// fs.access is low level API, it throws error when it doesn't match any of the flags
// is dir exists? writable? readable?
await fs.access(__dirname, oldfs.constants.F_OK | oldfs.constants.W_OK | oldfs.constants.R_OK);
} catch (error) {
console.log(`${__dirname} is not exists / writable / readable`);
}
})();
You can easily do it synchronously via existsSync()
.
But if you want to do it asynchronously, just do it like this:
await fs.promises.access("path");
Or put it within a try-catch like this...
try {
await fs.promises.access("path");
// The check succeeded
} catch (error) {
// The check failed
}