How to use the ensureDirSync function from fs-extra

Find comprehensive JavaScript fs-extra.ensureDirSync code examples handpicked from public code repositorys.

fs-extra.ensureDirSync is a function in the fs-extra library that creates a directory and all of its parent directories synchronously, if they do not already exist.

114
115
116
117
118
119
120
121
122
123
124
function createApp(name, verbose, useYarn, playAround = false) {
  const root = path.resolve(name);
  const appName = path.basename(root);


  checkAppName(appName);
  fs.ensureDirSync(name);
  if (!isSafeToCreateProjectIn(root, name)) {
    process.exit(1);
  }
  console.log();
fork icon109
star icon608
watch icon8

+ 4 other calls in file

4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
    } catch (e) {
       VlocityUtils.error('Failed to Delete Directory', sfdxTempFolder, e);
    }
}

fs.ensureDirSync(sfdxTempFolder);
fs.outputFileSync(path.join('sfdx-project.json'), JSON.stringify(salesforceProject), { encoding: 'utf8' });
fs.outputFileSync(path.join(sfdxTempFolder, '..', 'sfdx-project.json'), JSON.stringify({
    "packageDirectories": [
        {
fork icon82
star icon94
watch icon26

+ 3 other calls in file

How does fs-extra.ensureDirSync work?

The fs-extra.ensureDirSync function is a part of the fs-extra library, which is a collection of utility functions for working with the file system in Node.js. When you call the fs-extra.ensureDirSync function, you pass in a path to a directory as the first argument. The function then checks whether the directory exists, and creates it and all of its parent directories recursively if they do not already exist. If the directory already exists, the function does nothing and returns immediately. The fs-extra.ensureDirSync function is synchronous, meaning that it blocks the execution of the rest of your code until it has finished creating the directory. Overall, the fs-extra.ensureDirSync function provides a simple and reliable way to ensure that a directory exists in a Node.js application, creating the directory and all of its parent directories if necessary.

530
531
532
533
534
535
536
537
538
539

/** Check uib root folder: create if needed, writable? */
let uibRootFolderOK = true
// Try to create root and root/.config - ignore error if it already exists
try {
    fs.ensureDirSync(uib.configFolder) // creates both folders
    log.trace(`[uibuilder:runtimeSetup] uibRoot folder exists. ${uib.rootFolder}` )
} catch (e) {
    if ( e.code !== 'EEXIST' ) { // ignore folder exists error
        RED.log.error(`[uibuilder:runtimeSetup] Custom folder ERROR, path: ${uib.rootFolder}. ${e.message}`)
fork icon75
star icon352
watch icon25

+ 12 other calls in file

632
633
634
635
636
637
638
639
640
var ossFilePath   = `oss://${scriptMarket.configJSON.bucket}/${scriptMarket.configJSON.folder}/${file}`;
var localFilePath = path.join(localSavePath, file);
var ossEndpoint   = scriptMarket.configJSON.endpoint;

// 确保文件夹
fs.ensureDirSync(path.dirname(localFilePath));

// 删除原文件
fs.removeSync(localFilePath);
fork icon34
star icon185
watch icon0

Ai Example

1
2
3
const fs = require("fs-extra");

fs.ensureDirSync("/path/to/directory");

In this example, we first require the fs-extra module in our Node.js application. We then call the ensureDirSync function with the path to the directory /path/to/directory. The ensureDirSync function checks whether the directory exists, and creates it and all of its parent directories recursively if they do not already exist. If the directory already exists, the function does nothing and returns immediately. Overall, this example demonstrates how to use fs-extra.ensureDirSync to create a directory and all of its parent directories synchronously in a Node.js application using the fs-extra library.

2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
toolkit.createLimitedBuffer = function(limit) {
  return new LimitedBuffer(limit);
};


var createGitHandler = toolkit.createGitHandler = function(baseDir, timeout) {
  fs.ensureDirSync(baseDir);


  var git = simpleGit({
    baseDir: baseDir,
    timeout: { block: 15 * 1000 },
fork icon34
star icon183
watch icon6

+ 16 other calls in file

14
15
16
17
18
19
20
21
22
23
write(manifest) {
  if (!manifest) return { errors: ['Error writing manifest. Manifest is undefined.'] }
  const uriPathname = manifest.id.replace(this.baseURI, '')
  const outputPath = path.join(this.outputRoot, uriPathname)
  try {
    fs.ensureDirSync(path.parse(outputPath).dir)
    fs.writeJsonSync(outputPath, manifest)
    return { messages: [`Generated manifest ${outputPath}`] }
  } catch(error) {
    return { errors: [`Failed to write manifest. ${error}`] }
fork icon6
star icon63
watch icon15

+ 2 other calls in file

38
39
40
41
42
43
44
45
46
47
const resultDirPositive = `${resultDir}positive/`;

if (elementsToHide) {
  await helpers.hideElements(elementsToHide);
}
fs.ensureDirSync(resultDirPositive); // Make sure destination folder exists, if not, create it
const resultPathPositive = `${resultDirPositive}${filename}`;
await browser.saveScreenshot(resultPathPositive, async (err) => {
  await browser.pause(DELAY_500ms);
  if (err) {
fork icon29
star icon40
watch icon4

+ 4 other calls in file

157
158
159
160
161
162
163
164
165
166
if (this.fileData) {
  console.log('Uploading: ' + this.filename);
  this.uniquename = uuidv4() + '.zip';
  console.log("Created safe filename as '" + this.uniquename + "'");
  try {
    fs.ensureDirSync(plugindir);
  } catch (err) {
    console.log('Cannot Create Plugin Dir ' + plugindir);
  }
  fs.writeFile(plugindir + '/' + this.uniquename, this.fileData, (err) => {
fork icon28
star icon21
watch icon4

+ 20 other calls in file

705
706
707
708
709
710
711
712
713
_resolveMojangLibraries(tempNativePath){
    const nativesRegex = /.+:natives-([^-]+)(?:-(.+))?/
    const libs = {}

    const libArr = this.versionData.libraries
    fs.ensureDirSync(tempNativePath)
    for(let i=0; i<libArr.length; i++){
        const lib = libArr[i]
        if(Library.validateRules(lib.rules, lib.natives)){
fork icon3
star icon8
watch icon0

+ 11 other calls in file

139
140
141
142
143
144
145
146
147
148
    doValidate = true
} catch (err){
    logger.error(err)
    logger.info('Configuration file contains malformed JSON or is corrupt.')
    logger.info('Generating a new configuration file.')
    fs.ensureDirSync(path.join(configPath, '..'))
    config = DEFAULT_CONFIG
    exports.save()
}
if(doValidate){
fork icon0
star icon675
watch icon16

263
264
265
266
267
268
269
270
271
272
{
    // devices
    const mds = ds.boardMarkdownFiles()
    const mdo = "website/docs/devices"
    Object.keys(mds).forEach(fn => {
        fs.ensureDirSync(join(mdo, dirname(fn)))
        fs.writeFileSync(path.join(mdo, fn), mds[fn], {
            encoding: "utf-8",
        })
    })
fork icon4
star icon24
watch icon9

1155
1156
1157
1158
1159
1160
1161
1162
1163
1164

function make_build_environment(nodes, working_directory, options) {

    // Create target directory
    let dest = working_directory ?? fs.mkdtempSync(path.join(os.tmpdir(), app_name));
    fs.ensureDirSync(dest);

    // Create and initialize the manifest builder
    let mcu_nodes_root = path.resolve(__dirname, "./mcu_modules");
    let manifest = new mcuManifest.builder(library, mcu_nodes_root);
fork icon6
star icon20
watch icon3

+ 9 other calls in file

276
277
278
279
280
281
282
283
284
285
    return;
}

// prepare the dir for this manifest
let mnfst_path = path.join(destination, ...scoped_module, "manifest.json");
fs.ensureDirSync(path.dirname(mnfst_path));

/*  template: {
*       "modules": ['name of module to be resolved & included', 'another name', '* == all']
*   }
fork icon5
star icon18
watch icon3

+ 35 other calls in file

28
29
30
31
32
33
34
35
36
37
38
  return fs.existsSync(filePath);
}


function makeDir(path, dirName) {
  try {
    fse.ensureDirSync(path + dirName);
    return true;
  } catch (err) {
    console.error(err);
    return false;
fork icon0
star icon8
watch icon2

+ 4 other calls in file

352
353
354
355
356
357
358
359
360
361
  referenceTable(services, variables),
  "utf-8"
);

services.forEach(({ service, networks }) => {
  fs.ensureDirSync(`docs/api-reference/${toDashCase(service)}`);
  if (!fs.existsSync(`docs/api-reference/${toDashCase(service)}/index.mdx`)) {
    fs.writeFileSync(
      `docs/api-reference/${toDashCase(service)}/index.mdx`,
      frontMatterTemplate({
fork icon3
star icon5
watch icon17

+ 11 other calls in file

142
143
144
145
146
147
148
149
150
151
const landKey = landX.toString() + ':' + landZ.toString()
const savePath = this.voxel.landSaves
                 + this.voxel.data[landKey][1] + '/'
                 + ((parseInt(this.voxel.data[landKey][2]) > 7) ? 'futuristic' : 'fantasy')
                 + '/'
fse.ensureDirSync(savePath)
let bitmapObj, bitmapRaw
try {
  bitmapRaw = fs.readFileSync(savePath + "bitmap-" + slot.toString() + ".json", 'utf-8')
  bitmapObj = JSON.parse(bitmapRaw)
fork icon0
star icon4
watch icon3

+ 5 other calls in file

36
37
38
39
40
41
42
43
44
45
46
47
*/
function buildContentFile(path) {
  const contentDir = 'indexes/content-files';


  // Make sure the /flexContentFiles dir exists
  fse.ensureDirSync(contentDir);


  // contentPath: the file with extracted HTML text
  let parsedPath = path.split('/.vitepress/dist')[1];
  let contentPath = contentDir + parsedPath.replace('.html', '.json');
fork icon6
star icon1
watch icon6

1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
if(zipEntries[i].entryName === 'version.json'){
    const forgeVersion = JSON.parse(zip.readAsText(zipEntries[i]))
    const versionPath = path.join(commonPath, 'versions', forgeVersion.id)
    const versionFile = path.join(versionPath, forgeVersion.id + '.json')
    if(!fs.existsSync(versionFile)){
        fs.ensureDirSync(versionPath)
        fs.writeFileSync(path.join(versionPath, forgeVersion.id + '.json'), zipEntries[i].getData())
        resolve(forgeVersion)
    } else {
        //Read the saved file to allow for user modifications.
fork icon2
star icon1
watch icon0

+ 15 other calls in file

229
230
231
232
233
234
235
236
237
238
this.templateTarget = templateTarget;

const spinner = spinnerStart('正在页面安装模板...');

try {
  fse.ensureDirSync(templateSource);
  fse.ensureDirSync(templateTarget);
  fse.copySync(templateSource, templateTarget);
  Promise.resolve().then(() => log.success('页面模板安装完成'));
} catch (err) {
fork icon0
star icon2
watch icon2

+ 9 other calls in file

39
40
41
42
43
44
45
46
47
48
 * @return {string} real download directory
 */
const EnsureDonwloadPath = (_path) => {
    if (_path.startsWith('@')) {
        const relPath = _path.replace('@', '')
        fse.ensureDirSync(relPath)
        return relPath
    }
    const relPath = path.join(process.cwd(), _path)
    fse.ensureDirSync(relPath)
fork icon0
star icon1
watch icon1

+ 13 other calls in file

function icon

fs-extra.readFileSync is the most popular function in fs-extra (9724 examples)