How to check synchronously if a file/directory exists in Node.js

Overview

The existsSync method of the fs module is used to check if a file or directory exists in the file system.

Syntax

fs.existsSync(path)
Syntax of existsSync method

Parameters

path: This could be a string, URL, or buffer.

Return value

It returns true if the file exists, and false otherwise.

Example

index.js
temp.js
See index.js file for the code

Explanation

  • We have created a file with the name temp.js. This file can be viewed in the left side panel of the code widget.
  • Lines 3–15: We create a function, checkIfFileExists. This method uses the existsSync method to check if the file present in the provided path.
  • Line 17: We create a path variable with the file path, ./temp.js, as a value.
  • Line 18: We call the checkIfFileExists method with the path variable as an argument. This returns true.
  • Line 20: We assign the value, ./te.js, to the path variable.
  • Line 21: We call the checkIfFileExists method with the path variable as an argument. This returns false.

Free Resources