← Back to Node.js, page 1

nodejs-0017 · Medium mid

How do you check whether a file exists in Node.js, and why is 'check then use' a problem?

fs.exists is deprecated. fs.access or fs.stat tell you whether a file exists right now, but another process can create or delete it before your next step. The safe pattern is to act and handle the error, for example open with flag 'wx' to create a file only if it does not exist.

Full answer

Checking first and acting later is a time-of-check to time-of-use (TOCTOU) bug. Between "the file is not there" and "write the file", another process or another request can create it, and you overwrite its data. The same race exists for "the file is there, so read it", when someone deletes it in between.

Options:

  • fs.promises.access(path) resolves if the file is accessible and rejects with ENOENT otherwise. Fine for a quick check where a race does not matter, such as showing a message.
  • fs.promises.stat(path) also gives size and type.
  • fs.existsSync(path) is still supported and returns a boolean, but the same race applies. fs.exists (callback) is deprecated.
  • Do the real operation and handle the error. Open with the flag 'wx' to fail with EEXIST if the file already exists, 'r' to fail with ENOENT if it does not. The check and the action then happen in one atomic step in the operating system.

For "create the directory if needed", use fs.mkdir(path, { recursive: true }). It succeeds if the directory already exists. For "delete if present", use fs.rm(path, { force: true }), which ignores a missing file.

Lock files, atomic rename (write a temp file, then rename it over the target) and database transactions are the next tools when many processes share files.

javascript
const fsp = require('node:fs/promises');
const os = require('node:os');
const path = require('node:path');

async function main() {
  const dir = await fsp.mkdtemp(path.join(os.tmpdir(), 'lock-'));
  const lock = path.join(dir, 'job.lock');

  // Race-free "create only if missing": the OS decides who wins.
  const first = await fsp.open(lock, 'wx');
  await first.close();
  console.log('first process got the lock');

  try {
    await fsp.open(lock, 'wx');
  } catch (err) {
    console.log('second process failed with:', err.code);
  }

  // Idempotent helpers: safe to call twice.
  await fsp.mkdir(path.join(dir, 'a', 'b'), { recursive: true });
  await fsp.mkdir(path.join(dir, 'a', 'b'), { recursive: true });
  await fsp.rm(path.join(dir, 'does-not-exist'), { force: true });
  console.log('mkdir recursive and rm force did not throw');

  // A plain check works, but it can be stale a moment later.
  const exists = await fsp.access(lock).then(() => true, () => false);
  console.log('lock exists right now:', exists);

  await fsp.rm(dir, { recursive: true });
}

main();

The 'wx' flag means write, and fail if the path exists. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, same on two runs): first process got the lock second process failed with: EEXIST mkdir recursive and rm force did not throw lock exists right now: true

Key points

  • Check then act is a race condition (TOCTOU).
  • Use flags such as 'wx' to make the check part of the operation.
  • mkdir with recursive and rm with force are idempotent.
  • fs.exists is deprecated.

Common mistakes

  • Calling existsSync and then writeFileSync as if it were atomic.
  • Using the deprecated fs.exists.
  • Swallowing every error instead of checking for ENOENT.
  • Writing directly over a config file instead of writing a temp file and renaming it.

Follow-ups

  • How do you replace a file atomically?
  • How would two Node processes share a lock?
  • What does the 'ax' flag do?

Tips

  • Use the words 'race condition' and give the scenario.
  • Show the 'wx' flag, because it proves you know the safe pattern.
  • Mention rename for atomic updates as the next idea.