Node.js – How to create Directory | fs.mkdir()

  • by
node-js-fs-module-create-directory

Node.js – Create a new directory:

The inbuilt fs module in Node.js helps us to handle file and folders related operations. In the previous tutorial we saw how to create files and edit it using fs module. Here, we will learn how we can create new folders or directory.

fs is included in Node.js as a inbuilt module so we don’t need to install it using npm in our project. We just need to import in using requirefunction.

Creating new directory using fs.mkdir:

const fs = require('fs');

fs.mkdir('./folder1', (err) => {
if (err) {
console.log("error occurred in creating new directory", err);
return;
}

console.log("New directory created successfully");
})

This basic code will create a new directory at the provided path. The callback function will return error if it occurs.

node-js-fs-module-create-directory

As you can see folder1 was created inside the project folder once the code is executed. The problem with this code is, it will return an error if the folder is already present at the specified path with same name.

starting `node ./index.js`
error occurred in creating new directory [Error: EEXIST: file already exists, mkdir ‘D:\nodejs\FileSystem\folder1’] {
errno: -4075,
code: ‘EEXIST’,
syscall: ‘mkdir’,
path: ‘D:\\nodejs\\FileSystem\\folder1’
}

To avoid this error in creating directory we can use recursive option in our code like below:

const fs = require('fs');

fs.mkdir('./folder1',
{
recursive: true
}, (err) => {
if (err) {
console.log("error occurred in creating new directory", err);
return;
}

console.log("New directory created successfully");
});

fs.mkdir is an asynchronous functions accepting three arguments as below:

  1. Path (<String> | <Buffer> | <URL>) : Use to specify the path of the directory to be created.
  2. Mode ( <object> | <Integer>) : Optional parameter.
    1. recursive (default:false): When directory is already present, the callback gives an error when recursive is false.
    2. mode: Used to specify the permission of the directory. Default is 0o777
  3. callback : callback function. We can use the function to catch any error if occurred (shown in the above example).

Create Parent directory with new folders inside of it:

If you want to create a new directory and sub-folders inside of it, we can specify it by using folder path structure like:

./pDirectory/folder1/childFolder 

This will create childFolder inside of folder1 and folder1 will be created inside pDirectory

Example:

const fs = require('fs');

fs.mkdir('./pDirectory/folder1/childFolder',
{
recursive: true
}, (err) => {
if (err) {
console.log("error occurred in creating new directory", err);
return;
}

console.log("New directory created successfully");
});

node-js-fs-module-create-parent-child-directory-folder

Also see: