Node.js fs.extra ensureDir() Function
The ensureDir() function make sure that the directory user is requesting exists. If the directory structure does not exist the function will create the structure itself. mkdirs() and mkdirp() are the other names of the function which means we can use them in place of ensureDir() and everything will work as it is.
Syntax:
fs.ensureDir(dir,options,callback)
// OR
fs.mkdirs(dir,options,callback)
// OR
fs.mkdirp(dir,options,callback)
Parameters: This function accepts the following three parameters:
- dir: It is a string that contains the directory path.
- options: It is an object or an integer that is used to specify the optional parameters.
- Integer: If it is an integer it will be mode.
- Object: If it is an object it will be {mode: integer}.
- callback: It will be called after the task is completed by the function. It will either result in an error or success. Promises can also be used in place of the callback function.
Return value: It does not return anything.
Follow the steps to implement the function:
Step 1: The module can be installed by using the following command:
npm install fs-extra
Step 2: After the installation of the module you can check the version of the installed module by using this command:
npm ls fs-extra
Step 3: Create a file with the name index.js and require the fs-extra module in the file using the following command:
const fs = require('fs-extra');
Step 4: To run the file write the following command in the terminal:
node index.js
Project Structure: The project structure will look like this.
Example 1: Create a directory with the name ‘direc’. We will be passing this directory to the function.
index.js
const fs = require( "fs-extra" );
const dir = "direc" ;
fs.ensureDir(dir, (err) => {
if (err) return console.log(err);
console.log( "Directory exists" );
});
|
Run the index.js file using the following command:
node index.js
Output:
Directory exists
Example 2: This time we will be passing a directory structure that does not exist.
index.js
const fs = require( "fs-extra" );
const dir = "direc/dir" ;
const options = {
mode: 0o2775,
};
fs.ensureDir(dir, options)
.then(() => console.log( "Directory Structure Created" ))
. catch ((e) => console.log(e));
|
Run the index.js file using the following command:
node index.js
Output:
Directory Structure Created
Reference: https://github.com/jprichardson/node-fs-extra/blob/HEAD/docs/ensureDir.md
Last Updated :
07 Oct, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...