當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Node.js fs-extra ensureDirSync()用法及代碼示例

ensureDirSync()函數是ensureDir()函數的同步版本。該函數確保該目錄存在,如果目錄結構不存在,它將由該函數創建。也可以使用mkdirsSync()和mkdirpSync()代替ensureDirSync(),結果將相同。

用法:

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

參數:

  • dir:它是一個包含目錄路徑的字符串。
  • options:它是用於指定可選參數的對象或整數。
    1. Integer:如果是整數,則為mode。
    2. Object:如果是對象,則為{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}`);

輸出:

範例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


相關用法


注:本文由純淨天空篩選整理自pritishnagpal大神的英文原創作品 Node.js fs-extra ensureDirSync() function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。