Node.js | fs.mkdir() Method

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:



filter_none

edit
close

play_arrow

link
brightness_4
code

// 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!');
});

chevron_right


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.

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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!');
  });

chevron_right


Output:

Directory created successfully!

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




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.