Wednesday, 17 October 2018

node.js: fs.mkdir(path[, mode], callback): Create a directory asynchronously

fs.mkdir(path[, mode], callback)
This function creates a directory asynchronously. Callback function will be called on error cases.

Below table summarizes the arguments of mkdir function.
Argument
Type
Description
path
string or Buffer or URL
Specify the directory name to create
mode
integer
Default value is 0o777, it is not supported in Windows Operating System.
callback
Function
This function takes one argument ‘err’ and it is called when mkdir call is executed. On failure cases ‘err’ represents the stack trace.

Below table summarizes the modes supported by node.js
Constant (mode)
Octal value
Description
fs.constants.S_IRUSR
0o400
read by owner
fs.constants.S_IWUSR
0o200
write by owner
fs.constants.S_IXUSR
0o100
execute/search by owner
fs.constants.S_IRGRP        
0o40
read by group
fs.constants.S_IWGRP
0o20
write by group
fs.constants.S_IXGRP
0o10
execute/search by group
fs.constants.S_IROTH
0o4
read by others
fs.constants.S_IWOTH
0o2
write by others
fs.constants.S_IXOTH
0o1
execute/search by others
Find the below working application.

HelloWorld.js
var fs = require('fs');

var folderToCreate = 'testDir';

if (fs.existsSync(folderToCreate)) {
    console.log(`File ${folderToCreate} is already exists`);
} else {
    console.log(`File ${folderToCreate} is not exists, trying to create the directory`);
    fs.mkdir(folderToCreate, (error) => {
        if (error) {
            console.log(`Failed to create the directory ${folderToCreate}`);
        } else {
            console.log(`Directory ${folderToCreate} created successfully`);
        }

    });
}




Previous                                                 Next                                                 Home

No comments:

Post a Comment