Interview Q&A / Node.js

BeginnerQuick answer1 min readUpdated 3 Oct 2026

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

SHORT ANSWER

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

js
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 wx to fail if the file exists.

#nodejs#fs

Related questions

Practise more Node.js questions

Test your recall with short answers, then return to the detailed explanations when you need context.

Open Node.js quick answers →

Get new questions like this by email

One short email when something new and useful lands. No spam, unsubscribe in one tap.

By subscribing you agree to the Privacy Policy.