Skip to content
Related Articles

Related Articles

Node.js | fs.mkdir() Method
  • Last Updated : 08 Feb, 2021

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

Syntax

fs.mkdir(path, mode, callback)

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

  • path: This parameter holds the path of the directory 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 error. The recursive option if set to true will not give an error message if the directory to be created already exists.

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

Example 1:






// 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: This example illustrate the use to recursive option.




// 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!

Reference: https://nodejs.org/api/fs.html#fs_fs_mkdir_path_options_callback

My Personal Notes arrow_drop_up
Recommended Articles
Page :