---
title: "How do you check if a file exists in Node.js?"
description: "Use fs.existsSync for a quick synchronous check, or fs.promises.access in async code. Avoid check-then-open patterns that can race."
url: "https://bugsee.com/answers/nodejs/check-if-a-file-exists/"
---

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

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.

```js
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

- [How do you read command-line arguments in Node.js?](https://bugsee.com/answers/nodejs/read-command-line-arguments/)
