# Node.js: Check If a File Exists Synchronously

> Check if a file or directory exists synchronously in Node.js using fs.existsSync(), then use fs.lstatSync().isDirectory() to tell files from directories

**URL:** https://sentry.io/answers/check-if-a-file-or-directory-exists-synchronously-in-node-js/

---

## The Problem

How can I check synchronously if a file or directory exists in Node.js?

## The Solution

The function [`fs.existsSync()`](https://nodejs.org/api/fs.html#fsexistssyncpath) can be used to synchronously check if a file or directory exists. The asynchronous version of this function, [`fs.exists()`](https://nodejs.org/api/fs.html#fsexistspath-callback), is deprecated, but `fs.existsSync()` will still work.

Example usage:

```javascript
const fs = require("fs");

if (fs.existsSync("/tmp/myfile")) {
  console.log("/tmp/myfile exists!");
} else {
  console.log("/tmp/myfile does not exist!");
}
```

Note that this function will return True if `myfile` is a file or a directory, as long as it exists. We can use [`fs.lstatSync()`](https://nodejs.org/api/fs.html#fslstatsyncpath-options) on the path to retrieve an [`fs.Stats`](https://nodejs.org/api/fs.html#class-fsstats) object containing information about the path. This object has an [`isDirectory()`](https://nodejs.org/api/fs.html#statsisdirectory) method we can use:

```javascript
const fs = require("fs");

if (fs.existsSync("/tmp/myfile")) {
  console.log("/tmp/myfile exists!");

  if (fs.lstatSync("/tmp/myfile").isDirectory()) {
    console.log("/tmp/myfile is a directory!");
  } else {
    console.log("/tmp/myfile is a file!");
  }
} else {
  console.log("/tmp/myfile does not exist!");
}
```

---

*Source: [sentry.io/answers/check-if-a-file-or-directory-exists-synchronously-in-node-js/](https://sentry.io/answers/check-if-a-file-or-directory-exists-synchronously-in-node-js/)*
