fs.rmdir()方法用於刪除給定路徑下的目錄。還可以遞歸使用它來刪除嵌套目錄。
用法:
fs.rmdir( path, options, callback )
參數:此方法接受上述和以下所述的三個參數:
- path:它包含必須刪除的目錄的路徑。它可以是字符串,緩衝區或URL。
- options:該對象可用於指定將影響操作的可選參數。它具有三個可選參數:
- recursive:它是一個布爾值,它指定是否執行遞歸目錄刪除。在這種模式下,如果找不到指定的路徑並且在失敗時重試該操作,則不會報告錯誤。默認值為false。
- maxRetries:它是一個整數值,它指定Node.js由於任何錯誤而失敗時將嘗試執行該操作的次數。在給定的重試延遲後執行操作。如果遞歸選項未設置為true,則忽略此選項。默認值為0。
- retryDelay:它是一個整數值,它指定重試操作之前的等待時間(以毫秒為單位)。如果遞歸選項未設置為true,則忽略此選項。默認值為100毫秒。
- callback:執行該方法時將調用該函數。
- err:如果操作失敗,將引發此錯誤。
以下示例說明了Node.js中的fs.rmdir()方法:
範例1:本示例使用fs.rmdir()方法刪除目錄。
// Node.js program to demonstrate the
// fs.rmdir() method
// Import the filesystem module
const fs = require('fs');
// Get the current filenames
// in the directory
getCurrentFilenames();
fs.rmdir("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.rmdir()方法與遞歸參數一起使用以刪除嵌套目錄。
// Node.js program to demonstrate the
// fs.rmdir() method
// Import the filesystem module
const fs = require('fs');
// Get the current filenames
// in the directory
getCurrentFilenames();
// Trying to delete nested directories
// without the recursive parameter
fs.rmdir("directory_one", {
recursive:false,
}, (error) => {
if (error) {
console.log(error);
}
else {
console.log("Non Recursive:Directories Deleted!");
}
});
// Using the recursive option to delete
// multiple directories that are nested
fs.rmdir("directory_one", {
recursive:true,
}, (error) => {
if (error) {
console.log(error);
}
else {
console.log("Recursive: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 [Error:ENOTEMPTY:directory not empty, rmdir 'G:\tutorials\nodejs-fs-rmdir\directory_one'] { errno:-4051, code:'ENOTEMPTY', syscall:'rmdir', path:'G:\\tutorials\\nodejs-fs-rmdir\\directory_one' } Recursive:Directories Deleted! Current filenames: index.js package.json
參考: https://nodejs.org/api/fs.html#fs_fs_rmdir_path_options_callback
相關用法
注:本文由純淨天空篩選整理自sayantanm19大神的英文原創作品 Node.js | fs.rmdir() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。