62 lines
1.6 KiB
JavaScript
62 lines
1.6 KiB
JavaScript
const fs = require('fs');
|
|
const path = require('path');
|
|
|
|
/**
|
|
* 递归删除空目录
|
|
* @param {string} dirPath - 要检查的目录路径
|
|
* @param {boolean} dryRun - 是否只打印不删除
|
|
*/
|
|
function removeEmptyDirectories(dirPath, dryRun = false) {
|
|
try {
|
|
// 读取目录内容
|
|
const files = fs.readdirSync(dirPath);
|
|
|
|
// 递归检查子目录
|
|
for (const file of files) {
|
|
const fullPath = path.join(dirPath, file);
|
|
const stat = fs.statSync(fullPath);
|
|
|
|
if (stat.isDirectory()) {
|
|
removeEmptyDirectories(fullPath, dryRun);
|
|
}
|
|
}
|
|
|
|
// 再次读取目录内容,因为子目录可能已经被删除
|
|
const updatedFiles = fs.readdirSync(dirPath);
|
|
|
|
// 如果目录为空
|
|
if (updatedFiles.length === 0) {
|
|
console.log(`${dryRun ? 'Would remove' : 'Removing'} empty directory: ${dirPath}`);
|
|
if (!dryRun) {
|
|
fs.rmdirSync(dirPath);
|
|
}
|
|
}
|
|
} catch (error) {
|
|
console.error(`Error processing directory ${dirPath}:`, error.message);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 主函数
|
|
*/
|
|
function main() {
|
|
// 获取项目根目录
|
|
const projectRoot = path.resolve(__dirname, '..');
|
|
|
|
console.log('Starting to remove empty directories...');
|
|
console.log(`Project root: ${projectRoot}`);
|
|
console.log('====================================');
|
|
|
|
// 执行删除操作
|
|
removeEmptyDirectories(projectRoot);
|
|
|
|
console.log('====================================');
|
|
console.log('Empty directory cleanup completed!');
|
|
}
|
|
|
|
// 运行主函数
|
|
if (require.main === module) {
|
|
main();
|
|
}
|
|
|
|
module.exports = removeEmptyDirectories; |