fs.rmdirSync() 方法用於同步刪除給定路徑下的目錄。它也可以通過配置選項對象遞歸地用於刪除嵌套目錄。它返回 undefined.Syntax:
fs.rmdirSync( path, options )
參數:此方法接受上麵提到並在下麵描述的兩個參數:
- path:它包含必須刪除的目錄的路徑。它可以是字符串、緩衝區或 URL。
- options:它是一個對象,可用於指定將影響操作的可選參數。它有三個可選參數:
- recursive:它是一個布爾值,它指定是否執行遞歸目錄刪除。在這種模式下,如果找不到指定的路徑並且在失敗時重試該操作,則不會報告錯誤。默認值為false。
- maxRetries:它是一個整數值,它指定 Node.js 將嘗試執行操作的次數,如果由於任何錯誤而失敗。在給定的重試延遲後執行操作。如果遞歸選項未設置為 true,則忽略此選項。默認值為 0。
- retryDelay:它是一個整數值,指定重試操作之前等待的時間(以毫秒為單位)。如果遞歸選項未設置為 true,則忽略此選項。默認值為 100 毫秒。
下麵的示例說明了 Node.js 中的 fs.rmdirSync() 方法:示例 1:本示例使用 fs.rmdirSync() 方法刪除目錄。
javascript
// Node.js program to demonstrate the
// fs.rmdirSync() method
// Import the filesystem module
const fs = require('fs');
// Get the current filenames
// in the directory
getCurrentFilenames();
fs.rmdirSync("directory_one");
console.log("Folder Deleted!");
// Get the current filenames
// in the directory to verify
getCurrentFilenames();
// Function to get current filenames
// in directory
function getCurrentFilenames() {
console.log("\nCurrent filenames:");
fs.readdirSync(__dirname).forEach(file => {
console.log(file);
});
// console.log("\n");
}
輸出:
Current filenames: directory_one index.js package.json Folder Deleted! Current filenames: index.js package.json
範例2:本示例使用帶有遞歸參數的 fs.rmdirSync() 方法來刪除嵌套目錄。
javascript
// Node.js program to demonstrate the
// fs.rmdirSync() method
// Get the current filenames
// in the directory
getCurrentFilenames();
// Using the recursive option to delete
// multiple directories that are nested
fs.rmdirSync("directory_one", {
recursive:true,
});
console.log("Directories Deleted!");
// Get the current filenames
// in the directory to verify
getCurrentFilenames();
// Function to get current filenames
// in directory
function getCurrentFilenames() {
console.log("\nCurrent filenames:");
fs.readdirSync(__dirname).forEach(file => {
console.log(file);
});
console.log("\n");
}
輸出:
Current filenames: directory_one index.js package.json Directories Deleted! Current filenames: index.js package.json
參考: https://nodejs.org/api/fs.html#fs_fs_rmdirsync_path_options
相關用法
- Node.js console.timeLog()用法及代碼示例
- Node.js x509.toLegacyObject()用法及代碼示例
- Node.js process.nextTick()用法及代碼示例
- Node.js fs.fsyncSync()用法及代碼示例
- Node.js GM drawLine()用法及代碼示例
- Node.js GM drawArc()用法及代碼示例
- Node.js GM drawPolyline()用法及代碼示例
- Node.js GM drawBezier()用法及代碼示例
- Node.js GM drawCircle()用法及代碼示例
注:本文由純淨天空篩選整理自sayantanm19大神的英文原創作品 Node.js | fs.rmdirSync() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。