Open In App

Node fs.mkdir() Method

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:

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






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

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:




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


Article Tags :