# How to create a directory in Node.js

By Atta Ur Rehman Shah (https://attacomsian.com/about). Published Apr 10, 2020, updated Oct 1, 2022. Topics: Node.js.
Canonical URL: https://attacomsian.com/blog/nodejs-create-directory

> A quick guide to learning how to create a new directory in a Node.js application.

In a Node.js application, you can use the `mkdir()` method provided by the `fs` core module to create a new directory. This method works asynchronously to create a new directory at the given location.

Here is an example that demonstrates how you can use the `mkdir()` method to create a new folder:

```javascript
const fs = require('fs')

// directory path
const dir = './views'

// create new directory
fs.mkdir(dir, err => {
  if (err) {
    throw err
  }
  console.log('Directory is created.')
})
```

The above code will create a new directory called `views` in the current directory. However, if the `views` folder already exists in the current directory, it will throw an error.

To make sure that the directory is *only* created if it doesn't already exist, you can use the `existsSync()` method to check if the given [directory exists](https://attacomsian.com/blog/nodejs-check-if-directory-exists) or not.

Here is an example that checks for the existence of the directory before using the `mkdirSync()` method to create it:

```javascript
const fs = require('fs')

// directory path
const dir = './views'

// create new directory
try {
  // first check if the directory already exists
  if (!fs.existsSync(dir)) {
    fs.mkdirSync(dir)
    console.log('Directory is created.')
  } else {
    console.log('Directory already exists.')
  }
} catch (err) {
  console.log(err)
}
```

## Creating Parent Directories

What if you want to recursively create multiple nested directories that don't already exist?

You can pass an optional boolean parameter called `recursive` to the `mkdir()` and `mkdirSync()` methods to ensure that all parent folders are also created.

Let us look at the following example:

```javascript
const fs = require('fs')

// directory full path
const dir = './views/includes/layouts'

// recursively create multiple directories
fs.mkdir(dir, { recursive: true }, err => {
  if (err) {
    throw err
  }
  console.log('Directory is created.')
})
```

When the `recursive` parameter is `true`, the `mkdir()` method doesn't throw any error even if the path already exists. So it is safe to use it even when creating a single directory.

Read [this guide](https://attacomsian.com/blog/reading-writing-files-nodejs) to learn more about reading and writing files in a Node.js application.
