Checking if a directory exists

JavaScript:
Checking if a directory exists

How to:

In Node.js, since JavaScript itself doesn’t have direct access to the file system, the fs module is typically used for such operations. Here’s a simple way to check if a directory exists using fs.existsSync():

const fs = require('fs');

const directoryPath = './sample-directory';

// Check if the directory exists
if (fs.existsSync(directoryPath)) {
  console.log('Directory exists.');
} else {
  console.log('Directory does not exist.');
}

Sample Output:

Directory exists.

Or, for a non-blocking asynchronous approach, use fs.promises with async/await:

const fs = require('fs').promises;

async function checkDirectory(directoryPath) {
  try {
    await fs.access(directoryPath);
    console.log('Directory exists.');
  } catch (error) {
    console.log('Directory does not exist.');
  }
}

checkDirectory('./sample-directory');

Sample Output:

Directory exists.

For projects that make heavy use of file and directory operations, the fs-extra package, an extension of the native fs module, offers convenient additional methods. Here’s how you can achieve the same with fs-extra:

const fs = require('fs-extra');

const directoryPath = './sample-directory';

// Check if the directory exists
fs.pathExists(directoryPath)
  .then(exists => console.log(exists ? 'Directory exists.' : 'Directory does not exist.'))
  .catch(err => console.error(err));

Sample Output:

Directory exists.

This approach enables clean, readable code that seamlessly integrates with modern JavaScript practices.