How do you check whether a file exists in Node.js?
Use fs.promises.access in a try/catch, or fs.existsSync for quick sync checks. Better still, skip the check and handle the ENOENT error when you open the file, because the file can change between check and use.
Explain it simply
Checking if a seat is free and then walking to it can fail: someone else may sit down while you walk. Files behave the same way. If you check that a file exists and then open it, another process may delete it in between. That gap is called a race condition (the check-then-use bug).
Example
const fs = require("fs");
const fsp = require("fs/promises");
// 1. quick sync check, fine at start-up
if (fs.existsSync("./config.json")) {
console.log("config found");
}
// 2. async check
async function exists(file) {
try {
await fsp.access(file);
return true;
} catch {
return false;
}
}
// 3. often best: just try, and handle the error
async function readConfig() {
try {
return await fsp.readFile("./config.json", "utf8");
} catch (err) {
if (err.code === "ENOENT") return null; // file does not exist
throw err;
}
}fs.exists (callback version) is deprecated. fs.existsSync is not deprecated, but it blocks the thread.
What to say in the interview
"I use fsp.access for a simple check, but for real work I just try the operation and handle ENOENT, since checking first creates a race condition."
Common mistakes
- Using the deprecated
fs.exists. - Checking existence and then writing, instead of using flags like
wxto fail if the file exists.