To create a directory if it does not exist in Node.js, you can use the “fs.existsSync() and fs.mkdirSync()” methods.
Here is the step-by-step guide to create a Directory If It Doesn’t Exist in Node.js.
- Import the fs and path modules.
- Define the directory path.
- Check if the directory exists and create it if it does not.
Step 1: Import the fs and path modules
const fs = require('fs');
const path = require('path');
Step 2: Define the directory path
const directory = './newDir';
const dirPath = path.join(__dirname, directory);
Step 3: Check if the directory exists and create it if it doesn’t
const fs = require('fs');
const path = require('path');
const directory = './newDir';
const dirPath = path.join(__dirname, directory);
if (!fs.existsSync(dirPath)) {
fs.mkdirSync(dirPath, { recursive: true });
console.log('Directory created:', dirPath);
}
else {
console.log("Directory exists!")
}
Output
Directory created: /Users/krunallathiya/Desktop/Code/pythonenv/env/newDir
If you rerun the code above, it won’t be able to create a new directory because it already exists. So, it will return this output.
When you run the script, it will create the directory if it doesn’t exist and will log a message indicating whether the directory was created or if it already exists.
Note: Always ensure you have the appropriate permissions to create directories in the specified path.
That’s all!
Related posts
How to Check If File Exists in Node.js

Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.