How to Create Directories Using Node.js (Recursively) If Don't Exist

Robin
Updated on December 1, 2022

You can create a directory or nested directories in Node.js using mkdir() method. This method is available in the Node.js fs module.

There are 2 ways to create directories using NodeJS: Synchronously and Asynchronously. To create a folder asynchronously use mkdir() method. Otherwise use mkdirSync() method from fs module.

You can also check if a directory already exists in Node.js before trying to create it. This will prevent unwanted errors in your application.

Let's see how to generate folders both synchronously and asynchronously using Node.js modules. You will also learn how to create multi-level nested directories.

Asynchronously Create a Directory in Node.js If Doesn't Exit

We will use 2 methods from fs module to check and create a directory. In order to check whether the directory exists or not, we will apply the existsSync() method.

This method will return true if that folder is already available, otherwise false. When there is no folder with that name, call mkdir() method to create one.

          const fs = require('fs')
const { mkdir } = require('fs/promises')

const createFolder = async (path) => {
    try {
        if (!fs.existsSync(path)) {
            await mkdir(path)
            console.log('Folder created successfully')
        } else {
            console.log('Folder already exists')
        }
    } catch (error) {
        console.log(error)
    }
}

createFolder('./images')
        

In this example, I am creating a createFolder() function. It accepts a path where I want to create my directory. I will use try...catch block to handle any errors.

When I call this function, I am providing "./images" as its path argument. This means I want to create an images folder inside the current folder.

Let's check whether the images folder already exists or not with fs.existsSync() method. If it returns false then we will generate that folder using mkdir() method.

This function returns a promise. Therefore, I am putting the await keyword in front of it. That's how we can create a directory asynchronously.

Also Read: How to Get All Files in Directories (Recursively) with Node.js

Synchronously Create a Directory with Node.js If Doesn't Exit

To create a directory synchronously, we need to follow the same steps shown in the previous example. The only difference is that we will use mkdirSync() method from the fs module here instead of using mkdir() method.

          const fs = require('fs')

const createFolder = (path) => {
    try {
        if (!fs.existsSync(path)) {
            fs.mkdirSync(path)
            console.log('Folder created successfully')
        } else {
            console.log('Folder already exists')
        }
    } catch (error) {
        console.log(error)
    }
}

createFolder('./images')
        

As you can see, I have the createFolder() function that accepts the folder path. Then I am checking whether the folder is already available or not in that path using fs.existsSync() method.

To generate the actual directory, call fs.mkdirSync() method and pass the path as its argument. It will not return anything as this method creates the directory synchronously.

But when we do it synchronously, it will block the main thread. That means JavaScript will stop executing other code until the fs.mkdirSync() method completes.

That's why it is recommended to use asynchronous methods as much as possible. You can learn more about the differences between synchronous and asynchronous programming if you want.

Create Nested Folders Using Node.js Recursively

Sometimes we need to create nested folders recursively. But we have to make a simple change to do so in the previous process. Otherwise, it might give you an error.

For example, I want to create nested folders "./images/profile" like this. I have to create an images directory and a profile directory inside that.

          const fs = require('fs')
const { mkdir } = require('fs/promises')

const createFolder = async (path) => {
    try {
        if (!fs.existsSync(path)) {
            await mkdir(path, {
                recursive: true,
            })
            console.log('Folder created successfully')
        } else {
            console.log('Folder already exists')
        }
    } catch (error) {
        console.log(error)
    }
}

createFolder('./images/profile')
        

When we pass "./images/profile" in the mkdir() method, it will throw an error if there is no images folder. This method can't create multiple directories at the same time by default.

To generate these nested directories, you have to set an option. You can do this by giving a second argument for the method. We pass an object in the second argument and set the recursive property to true.

When we set this option in the mkdir() method, it will create an images directory and then the profile directory inside that. Now, you can create as many nested directories as you want.

Also Read: Node.js Cluster: Improve Server Performance with Clustering

Conclusion

You have learned 2 methods from the Node.js fs module in this article. Use mkdir() method to generate a folder asynchronously or use mkdirSync() method to do it synchronously.

We can apply any of those techniques to create directories or nested directories recursively in Node.js if don't exist.

Related Posts