how to use the ensuredirsync function from fs-extra in javascript

To use the ensureDirSync() function from the fs-extra package in Node.js, you need to follow the below steps:

  1. Install fs-extra package using npm, using the command:

    index.tsx
    npm install fs-extra
    
    21 chars
    2 lines
  2. Import the fs-extra package in your JavaScript file:

    index.tsx
    const fs = require("fs-extra");
    
    32 chars
    2 lines
  3. Call the ensureDirSync() function and pass the directory path as a parameter to create the directory if it does not exist.

    index.tsx
    const directoryPath = "./myFolder";
    fs.ensureDirSync(directoryPath);
    
    69 chars
    3 lines

    If the directory already exists, this function will not modify it in any way.

  4. You can also pass an options object with some properties to modify the behavior of the function.

    index.tsx
    const directoryPath = "./myFolder";
    const options = {
        mode: 0o2775
    };
    fs.ensureDirSync(directoryPath, options);
    
    116 chars
    6 lines

    In the above example, 0o2775 represents the mode of the directory (in octal notation). The ensureDirSync() function will create the directory with the mode specified in the options object.

That's it! The ensureDirSync() function will create the specified directory if it does not exist and return silently if it already exists.

gistlibby LogSnag