Open In App

Node fs.mkdir() Method

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

The fs.mkdir() method in Node.js is used to create a directory asynchronously.

Syntax

fs.mkdir(path, mode, callback)

Parameters: This method accepts three parameters as mentioned above and described below:

  • path: This parameter holds the path of the directory that has to be created.
  • mode: This parameter holds the recursive boolean value. The mode option is used to set the directory permission, by default it is 0777.
  • callback: This parameter holds the callback function that contains an error. The recursive option if set to true will not give an error message if the directory to be created already exists.

Example 1: Below examples illustrate the use of fs.mkdir() method in Node.js:

Javascript




// Node.js program to demonstrate the
// fs.mkdir() Method
 
// Include fs and path module
const fs = require('fs');
const path = require('path');
 
fs.mkdir(path.join(__dirname, 'test'),
    (err) => {
        if (err) {
            return console.error(err);
        }
        console.log('Directory created successfully!');
    });


Output:

Directory created successfully!
  • Directory Structure Before running the code:
  • Directory Structure After running the code:

Note: If you will run this program again, then it will display an error message as the directory already exists. To overcome this error we will use the recursive option.

Example 2: Below examples illustrate the use of fs.mkdir() method in Node.js, This example illustrate the use to recursive option:

Javascript




// Node.js program to demonstrate the
// fs.mkdir() Method
 
// Include fs and path module
const fs = require('fs');
const path = require('path');
 
fs.mkdir(path.join(__dirname, 'test'),
    { recursive: true },
    (err) => {
        if (err) {
            return console.error(err);
        }
        console.log('Directory created successfully!');
    });


Output:

Directory created successfully!

We have a complete list of Node File System module methods, to check those please go through this Node File System Complete Reference article.



Last Updated : 14 Jan, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads