Use fs.existsSync(path) for a quick synchronous check, or await fs.promises.access(path) in async code, catching the error when the file is missing.
import { existsSync } from "node:fs";
import { access, readFile } from "node:fs/promises";
existsSync("config.json"); // true or false
async function exists(path) {
try {
await access(path);
return true;
} catch {
return false;
}
}
// Better: skip the check and handle the error when you open the file
try {
const text = await readFile("config.json", "utf8");
} catch (err) {
if (err.code !== "ENOENT") throw err;
}Checking first and opening afterwards leaves a gap in which another process can create or delete the file. When you intend to use the file, attempt the operation and handle ENOENT instead.
