pathExists()測試給定的文件路徑是否存在。它在引擎蓋下使用fs.access()。
用法:
fs.pathExists(file,callback)
參數:該函數接受上述和以下所述的兩個參數:
- file:它是一個包含文件路徑的字符串。
- callback:函數執行後將調用它。它將導致錯誤或稱為存在的布爾值。我們也可以使用Promise代替回調函數。
返回值:它不返回任何東西。
請按照以下步驟實現該函數:
可以使用以下命令安裝該模塊:
npm install fs-extra
安裝模塊後,可以使用以下命令檢查已安裝模塊的版本:
npm ls fs-extra
使用以下命令創建一個名為index.js的文件,並在文件中需要fs-extra模塊:
const fs = require('fs-extra');
要運行文件,請在終端中輸入以下命令:
node index.js
項目結構:項目結構如下所示:
範例1:
index.js
// Requiring module
const fs = require("fs-extra");
// This file already
// exists so function
// will return true
const file = "file.txt";
// Function call
// Using callback function
fs.pathExists(file, (err, exists) => {
if (err) return console.log(err);
console.log(exists);
});
輸出:這將是控製台輸出。
範例2:
index.js
// Requiring module
const fs = require("fs-extra");
// This file doesn't
// exists so function
// will return false
const file = "dir/file.txt";
// Function call
// Using Promises
fs.pathExists(file)
.then((exists) => console.log(exists))
.catch((e) => console.log(e));
輸出:這將是控製台輸出。
相關用法
- Node.js GM solarize()用法及代碼示例
- Node.js MySQL Max()用法及代碼示例
- Node.js process.nextTick()用法及代碼示例
- PHP imagecreatetruecolor()用法及代碼示例
注:本文由純淨天空篩選整理自pritishnagpal大神的英文原創作品 Node.js fs-extra pathExists() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。