How to check if a Directory exists in Node.js [6 Ways]

avatar
Borislav Hadzhiev

Last updated: Apr 5, 2024
5 min

banner

# Table of Contents

  1. How to check if a Directory exists in Node.js
  2. Check if a directory exists using fs.access() in Node.js
  3. How to check if a Directory exists using fs.stat in Node.js
  4. How to check if a Directory exists using fs-extra in Node.js

# How to check if a Directory exists in Node.js

You can use the fs.existsSync() method to check if a directory exists in Node.js.

The method takes the path to the directory and returns true if it exists and false otherwise.

index.js
import fs from 'fs'; // ๐Ÿ‘‡๏ธ if you use CommonJS // const fs = require('fs') const directoryPath = './my-folder'; if (fs.existsSync(directoryPath)) { console.log('The directory exists'); } else { console.log('The directory does NOT exist'); }

check if directory exists in node js

The code for this article is available on GitHub

The fs.existsSync() method synchronously checks if the supplied path exists.

The path can point to a directory or a file.

If the path exists, the method returns true, otherwise, false is returned.

The code sample above uses the ES6 modules import/export syntax.

If you use the CommonJS require() syntax, use the following import statement instead.

index.js
// ๐Ÿ‘‡๏ธ if you use CommonJS const fs = require('fs'); // ... rest of the code

If you need to create the directory if it doesn't exist, use the fs.mkdirSync method.

index.js
import fs from 'fs'; // ๐Ÿ‘‡๏ธ if you use CommonJS // const fs = require('fs') const directoryPath = './my-folder'; if (fs.existsSync(directoryPath)) { console.log('The directory exists'); } else { console.log('The directory does NOT exist'); fs.mkdirSync(directoryPath); }
The code for this article is available on GitHub

The fs.mkdirSync() method takes a path as a parameter and synchronously creates a directory.

If you want to recursively create the directory if it doesn't exist, set the recursive property to true in the options object.

index.js
import fs from 'fs'; // ๐Ÿ‘‡๏ธ if you use CommonJS // const fs = require('fs') const directoryPath = './my-folder'; if (fs.existsSync(directoryPath)) { console.log('The directory exists'); } else { console.log('The directory does NOT exist'); fs.mkdirSync(directoryPath, {recursive: true}); }

Note that the fs.existsSync() method can also be used to check if a file exists.

index.js
import fs from 'fs'; // ๐Ÿ‘‡๏ธ if you use CommonJS // const fs = require('fs') const filePath = './my-file.txt'; if (fs.existsSync(filePath)) { console.log('The file exists'); } else { console.log('The file does NOT exist'); }

We called the fs.existsSync() method with a file path and not with a directory path in the example.

# Check if a directory exists using fs.access() in Node.js

You can also use the fs.access() method to check if a directory exists.

index.js
import fs from 'fs'; // ๐Ÿ‘‡๏ธ if you use CommonJS // const fs = require('fs') const directoryPath = './my-folder'; fs.access(directoryPath, error => { if (error) { console.log(error.message); if (error.code === 'ENOENT') { console.log('The directory does not exist'); // ๐Ÿ‘‡๏ธ optionally create the directory fs.mkdirSync(directoryPath, {recursive: true}); } } else { console.log('The directory exists'); } });

check if directory exists using fs access

The code for this article is available on GitHub

The first argument we passed to the fs.access() method is the path to the directory and the second is a callback function.

If the file doesn't exist, the error parameter will be an Error object.

The nested if statement checks if the code property of the error object is equal to ENOENT.

If the condition is met, the directory doesn't exist.

You can optionally create the directory by using the fs.mkdirSync method.

If the else block runs, then the directory exists.

You can also check if the directory exists in the if statement by checking if the error parameter is falsy.

index.js
import fs from 'fs'; // ๐Ÿ‘‡๏ธ if you use CommonJS // const fs = require('fs') const directoryPath = './my-folder'; fs.access(directoryPath, error => { if (!error) { console.log('The directory exists'); } else { console.log(error.message); if (error.code === 'ENOENT') { console.log('The directory does not exist'); // ๐Ÿ‘‡๏ธ Optionally create the directory fs.mkdirSync(directoryPath, {recursive: true}); } } });
The code for this article is available on GitHub

The if statement checks if no error occurred.

If the condition is met, then the directory exists.

You can also use the async/await syntax to check if a directory exists.

index.js
import fs from 'fs/promises'; // ๐Ÿ‘‡๏ธ If you use CommonJS // const fs = require('fs/promises') async function checkIfDirectoryExists(dirPath) { try { await fs.access(dirPath); console.log('The directory exists'); } catch (error) { console.log(error.message); if (error.code === 'ENOENT') { console.log('The directory does NOT exist'); await fs.mkdir(dirPath, {recursive: true}); } } } const directoryPath = './my-folder'; checkIfDirectoryExists(directoryPath).then(() => { console.log('This runs after the Promise resolves'); });

check if directory exists using fs access async await

Notice that we imported fs from fs/promises this time.

The fsPromises.access() method returns a Promise that we can await.

If the Promise resolves, then the directory exists.

If an error occurs, then the catch() method runs.

We check if the code property of the Error object is ENOENT and create a directory at the specified path.

# How to check if a Directory exists using fs.stat in Node.js

You can also use the fs.statSync method to check if a directory exists in Node.js.

index.js
import fs from 'fs'; // ๐Ÿ‘‡๏ธ If you use CommonJS // const fs = require('fs') const directoryPath = './my-folder'; try { if (fs.statSync(directoryPath).isDirectory()) { console.log('The directory exists'); } } catch (err) { console.log(err.message); console.log('The directory does NOT exist'); if (err.code === 'ENOENT') { fs.mkdirSync(directoryPath, {recursive: true}); } }

check if directory exists using fs statsync

The code for this article is available on GitHub

We used the fs.statSync() method to get an fs.Stats object on which we can call the isDirectory() method to check if the path is a directory.

If the condition is met, the directory exists.

Otherwise, an error is raised and the catch() method runs.

In the catch() method, we check if the code property of the Error object is equal to ENOENT.

If the condition is met, then the directory doesn't exist, so we create it using fs.mkdirSync().

You can also use the asynchronous fs.stat() method to check if a directory exists.

index.js
import fs from 'fs/promises'; // ๐Ÿ‘‡๏ธ if you use CommonJS // const fs = require('fs/promises') async function checkIfDirectoryExists(dirPath) { try { const stats = await fs.stat(dirPath); if (stats.isDirectory()) { console.log('The directory exists'); } } catch (err) { console.log(err.message); console.log('The directory does NOT exist'); if (err.code === 'ENOENT') { await fs.mkdir(directoryPath, {recursive: true}); } } } const directoryPath = './my-folder'; checkIfDirectoryExists(directoryPath).then(() => { console.log('This runs after the Promise has resolved'); });
The code for this article is available on GitHub

Notice that we imported the fs module from fs/promises to be able to use the async version of the fs methods.

We assign the stats object to a variable and check if the supplied path is a valid directory.

If the condition is met, then the directory exists.

Otherwise, the directory doesn't exist and we create it in the catch() block.

# How to check if a Directory exists using fs-extra in Node.js

You can also use the popular fs-extra module to check if a directory exists.

First, make sure you have the module installed.

Open your terminal in your project's root directory (where your package.json file is) and run the following command.

shell
npm init -y # with NPM npm install fs-extra # or with YARN yarn add fs-extra

Now import and use the fs-extra module as follows.

index.js
import fs from 'fs-extra'; // ๐Ÿ‘‡๏ธ if you use CommonJS // const fs = require('fs-extra') async function checkIfDirectoryExists(dirPath) { try { const exists = await fs.pathExists(dirPath); if (exists) { console.log('The directory exists'); } else { console.log('The directory does NOT exist'); await fs.ensureDir(dirPath); } } catch (err) { console.log(err.message); } } const directoryPath = './my-folder'; checkIfDirectoryExists(directoryPath).then(() => { console.log('This runs after the Promise has resolved'); });

check if directory exists using fs extra

The code for this article is available on GitHub

The fs.pathExists() method tests whether the given path exists.

The method returns true if the specified path exists and false otherwise.

If the directory doesn't exist, you can use the fs.ensureDir() method to create it.

The method ensures that the directory exists.

If the directory structure doesn't exist, it is created.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev