How to Create a Directory If It Doesn’t Exist in Node.js

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.

  1. Import the fs and path modules.
  2. Define the directory path.
  3. 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.

Check if the directory exists and create it if it doesn't

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

Leave a Comment