📜  Node.js fs-extra ensureDirSync()函数

📅  最后修改于: 2022-05-13 01:56:21.430000             🧑  作者: Mango

Node.js fs-extra ensureDirSync()函数

ensureDirSync()函数是 ensureDir()函数的同步版本。该函数确保目录存在,如果目录结构不存在,它将由函数创建。 mkdirsSync()mkdirpSync()也可以用来代替 ensureDirSync() 并且结果是一样的。

句法:

ensureDirSync(dir,options)
// OR
mkdirsSync(dir,options)
// OR
mkdirpSync(dir,options)

参数:

  • dir:它是一个包含目录路径的字符串。
  • options:它是一个对象或整数,用于指定可选参数。
    1. 整数:如果是整数,则为模式。
    2. 对象:如果它是一个对象,它将是 {mode: integer}。

返回值:它不返回任何东西。

按照以下步骤实现该函数:

  1. 可以使用以下命令安装该模块。
    npm install fs-extra
  2. 安装模块后,您可以使用此命令检查已安装模块的版本。
    npm ls fs-extra

  3. 创建一个名为 index.js 的文件,并使用以下命令在文件中要求 fs-extra 模块。
    const fs = require('fs-extra');
  4. 要运行该文件,请在终端中写入以下命令。
    node index.js

项目结构:项目结构将如下所示。

示例 1:

index.js
// Requiring module
const fs = require("fs-extra");
  
// Function to check
// if directory  exists
// or not
const dirExists = (dir) => {
  if (fs.existsSync(dir)) {
    return "Directory exists";
  } else {
    return "Directory do not exist";
  }
};
  
// This directory
// already exists so
// function will not
// do anything
const dir = "dir";
  
// Checking before
// calling function
const before = dirExists(dir);
console.log(`Before function call ${before}`);
  
// Function call
fs.ensureDirSync(dir);
  
// Checking after
//  calling function
const after = dirExists(dir);
console.log(`After function call ${after}`);


index.js
// Requiring module
const fs = require("fs-extra");
  
// Function to check
// if directory  exists
// or not
const dirExists = (dir) => {
  if (fs.existsSync(dir)) {
    return "Directory exists";
  } else {
    return "Directory do not exist";
  }
};
  
// This directory
// do not  exists so
// function will create
// the directory
const dir = "direc/dir";
  
const mode = 0o2775;
  
// Checking before
// calling function
const before = dirExists(dir);
console.log(`Before function call ${before}`);
  
// Function call
fs.ensureDirSync(dir, mode);
  
// Checking after
//  calling function
const after = dirExists(dir);
console.log(`After function call ${after}`);


输出:

示例 2:

index.js

// Requiring module
const fs = require("fs-extra");
  
// Function to check
// if directory  exists
// or not
const dirExists = (dir) => {
  if (fs.existsSync(dir)) {
    return "Directory exists";
  } else {
    return "Directory do not exist";
  }
};
  
// This directory
// do not  exists so
// function will create
// the directory
const dir = "direc/dir";
  
const mode = 0o2775;
  
// Checking before
// calling function
const before = dirExists(dir);
console.log(`Before function call ${before}`);
  
// Function call
fs.ensureDirSync(dir, mode);
  
// Checking after
//  calling function
const after = dirExists(dir);
console.log(`After function call ${after}`);

输出:

参考: https://github.com/jprichardson/node-fs-extra/blob/HEAD/docs/ensureDir-sync.md