Skip to content
Related Articles

Related Articles

NodeJS fs.extra ensureDir() Function
  • Last Updated : 23 Feb, 2021

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:

  1. dir: It is a string that contains the directory path.
  2. 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}.
  3. 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




// Requiring module
const fs = require("fs-extra");
  
// The directory already
// exists so function will do nothing
const dir = "direc";
  
// Function call using callback functions
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




// Requiring module
const fs = require("fs-extra");
  
// The directory structure
// does not exist so function will create it
const dir = "direc/dir";
  
// Additional options Specifying mode
const options = {
  mode: 0o2775,
};
  
// Function call using Promises
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

My Personal Notes arrow_drop_up
Recommended Articles
Page :