📅  最后修改于: 2023-12-03 15:17:54.517000             🧑  作者: Mango
fsPromises.rmdir()
方法用于删除文件夹。
fsPromises.rmdir(path, options)
path
:待删除的文件夹的路径。options
:可选参数对象,包括:recursive
:布尔值,表示是否递归地删除子文件夹和文件。默认值为 false
。maxRetries
:整数值,表示在删除过程中失败后最多重试的次数。默认为 0,即不重试。retryDelay
:整数值,表示在删除失败后重试之前等待的毫秒数。默认为 1000。一个Promise对象,如果删除成功则resolve,否则reject。
const fsPromises = require('fs').promises;
async function deleteDir(path) {
try {
await fsPromises.rmdir(path);
console.log(`Deleted directory: ${path}`);
} catch (err) {
console.error(`Error deleting directory ${path}:`, err);
}
}
deleteDir('./myFolder');
const fsPromises = require('fs').promises;
async function deleteDirRecursive(path) {
try {
await fsPromises.rmdir(path, { recursive: true });
console.log(`Recursively deleted directory: ${path}`);
} catch (err) {
console.error(`Error recursively deleting directory ${path}:`, err);
}
}
deleteDirRecursive('./myFolder');
const fsPromises = require('fs').promises;
async function deleteDirWithRetry(path) {
let retries = 0;
let maxRetries = 3;
let retryDelay = 1000;
while (retries < maxRetries) {
try {
await fsPromises.rmdir(path);
console.log(`Deleted directory: ${path}`);
return;
} catch (err) {
console.error(`Error deleting directory ${path}:`, err);
retries++;
await new Promise(resolve => setTimeout(resolve, retryDelay));
}
}
console.error(`Max retries (${maxRetries}) reached for deleting directory ${path}`);
}
deleteDirWithRetry('./myFolder');