Last updated: Apr 5, 2024
Reading timeยท5 min

fs-extra in Node.jsYou 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.
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'); }

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.
// ๐๏ธ 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.
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 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.
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.
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.
fs.access() in Node.jsYou can also use the fs.access() method to check if a directory exists.
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'); } });

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.
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.
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 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.
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'); });

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.
fs.stat in Node.jsYou can also use the fs.statSync method to check if a directory exists in
Node.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}); } }

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.
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'); });
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.
fs-extra in Node.jsYou 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.
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.
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'); });

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.
You can learn more about the related topics by checking out the following tutorials: