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


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

ensureFileSync()函數是ensureFile()函數的同步版本。該函數確保該文件存在,如果文件不存在,它將由該函數創建。如果請求的文件位於不存在的目錄中,則目錄和其中的文件將由函數本身創建。如果該文件已經存在,則不會被修改。也可以使用createFileSync()函數代替ensureFileSync()函數,其結果將相同。

用法:

fs.ensureFileSync(file)

或者

fs.createFileSync(file)

參數:

  • file:它是一個包含文件路徑的字符串。

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

請按照以下步驟實現該函數:

  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 file exists
// or not
const fileExists = (file) => {
  if (fs.existsSync(file)) {
    return "File exists";
  } else {
    return "File do not exist";
  }
};
  
// This file already
// exist so function
// will not do anything
const file = "file.txt";
  
// Checking before
// calling function
const before = fileExists(file);
console.log(`Before function call ${before}`);
  
// Function call
fs.ensureFileSync(file);
  
// Checking after calling function
const after = fileExists(file);
console.log(`After function call ${after}`);

輸出:

範例2:

index.js


// Requiring module
const fs = require("fs-extra");
  
// Function to check
// if file exists
// or not
const fileExists = (file) => {
  if (fs.existsSync(file)) {
    return "File exists";
  } else {
    return "File do not exist";
  }
};
  
// This file and directory
// do not exist so both
// will be created
const file = "dir/file.txt";
  
// Checking before
// calling function
const before = fileExists(file);
console.log(`Before function call ${before}`);
  
// Function call
fs.ensureFileSync(file);
  
// Checking after calling function
const after = fileExists(file);
console.log(`After function call ${after}`);

輸出:

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


相關用法


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