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

Better Stack Team
Updated on March 11, 2024

In Node.js, you can use the fs (file system) module to check synchronously if a file or directory exists. The fs.existsSync() function can be used for this purpose. Here's an example:

 
const fs = require('fs');

const pathToFileOrDir = '/path/to/your/file_or_directory';

// Check if the file or directory exists synchronously
if (fs.existsSync(pathToFileOrDir)) {
  console.log(`The file or directory at '${pathToFileOrDir}' exists.`);
} else {
  console.log(`The file or directory at '${pathToFileOrDir}' does not exist.`);
}

Replace '/path/to/your/file_or_directory' with the actual path to the file or directory you want to check.

Please note that using synchronous methods, like fs.existsSync(), can block the event loop, and it is generally recommended to use asynchronous methods to avoid blocking your application. However, in some specific scenarios, synchronous methods might be appropriate.

If you prefer an asynchronous approach, you can use the fs.stat() function:

 
const fs = require('fs');

const pathToFileOrDir = '/path/to/your/file_or_directory';

// Check if the file or directory exists asynchronously
fs.stat(pathToFileOrDir, (err, stats) => {
  if (err) {
    console.log(`The file or directory at '${pathToFileOrDir}' does not exist.`);
  } else {
    console.log(`The file or directory at '${pathToFileOrDir}' exists.`);
  }
});

In the asynchronous example, the fs.stat() function is used to get information about the file or directory. The presence of an error in the callback indicates that the file or directory does not exist.

Got an article suggestion? Let us know
Explore more
Licensed under CC-BY-NC-SA

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.