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:
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 or not.
Here is an example that checks for the existence of the directory before using the mkdirSync()
method to create it:
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:
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 to learn more about reading and writing files in a Node.js application.
✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.