Create a directory if it doesn’t exist using Node.js

This tutorial will show you how to check if a directory exists or not and create the directory if it does not exist using Node.js.

For this purpose, we need the fs module which is the file system module that allows us to work with the file system on our computer.

First of all, we will check if a directory exists or not.

To import fs (file system) module, we have to use require() method like below.

let fs = require('fs')

Using the fs module we can access all the fs properties or methods.

const dir = "nodejs";

In the above program, I have stored the directory name which I want to create in a variable. First, we need to check whether this nodejs directory exists or not. If not exist we will create that directory.

fs.exists(dir, function (exist) {
    if (exist) {
        console.log('Directory exists');
    }
})

In the above program, the fs.exists() method to check whether the directory exists or not. This method accepts two parameters. The first parameter we need to pass is dir which is nodejs the name of the directory that we want to create or check. The second one is a callback function.

If the directory exists we will get an output Directory exists.

else {
    console.log('Directory need to create');
}

And if the directory not exists we will get an output Directory need to create.

Here’s the complete code below.

let fs = require('fs');
const dir = "nodejs";

fs.exists(dir, function (exist) {
    if (exist) {
        console.log('Directory exists');
    }
    else {
        console.log('Directory need to create');
    }
})

To run this program, just go into the terminal and write node then give a space and write your file name then press enter like below.

PS G:\saM> node index.js

If you run the above program you will get an output Directory exists if the directory which you want to create exists. Otherwise, you will get Directory need to create as output if the directory doesn’t exist.

Now, If the directory doesn’t present we can make it by using fs.mkdirSync() method. This method creates a directory Synchronously.

fs.mkdirSync(dir);

In the above program, the fs.mkdirSync() method to create the directory. And passed a parameter dir which is nodejs the name of the directory that we want to create.

Here’s the complete code below.

let fs = require('fs');
const dir = "nodejs";

fs.exists(dir, function (exist) {
    if (exist) {
        console.log('Directory exists');
    }
    else {
        fs.mkdirSync(dir);
        console.log('Directory created');
    }
})

If you run the above program, first it will check if the directory called nodejs exists or not if  exist it will show Directory exists as output. If not then it will create the directory and show Directory created as output.

Leave a Reply

Your email address will not be published. Required fields are marked *