How do you check if a file exists in Node.js?

← Node.js answers

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.

Related questions

Start debugging smarter today

Try Bugsee for free — no commitments, no hidden fees.

Free sign upLive demoNo credit card required