const fs = require('fs');
const path = require('path');
function deleteGitFolders(directory, depth, deleteDirName) {
if (depth === 0) {
return;
}
fs.readdir(directory, (err, files) => {
if (err) {
console.error('Error reading directory:', err);
return;
}
console.log(files)
files.forEach(file => {
const filePath = path.join(directory, file);
if (fs.statSync(filePath).isDirectory()) {
if (file === deleteDirName) {
console.log('Deleting .git directory:', filePath);
fs.rmdir(filePath, { recursive: true }, err => {
if (err) {
console.error('Error deleting .git directory:', err);
} else {
console.log('.git directory deleted successfully:', filePath);
}
});
} else {
deleteGitFolders(filePath, depth - 1); // 递归调用,深度减一
}
}
});
});
}
const startDirectory = './';
deleteGitFolders(startDirectory, 2, '.git'); // 限制递归深度为2
如果你要使用只需要deleteGitFolders(startDirectory, 2, '.git'); 改成你指定的目录,你要递归的层级,你要删除的目录名
直接无限层级递归
const fs = require('fs');
const path = require('path');
function deleteGitFolders(directory) {
fs.readdir(directory, (err, files) => {
if (err) {
console.error('Error reading directory:', err);
return;
}
files.forEach(file => {
console.log(file)
const filePath = path.join(directory, file);
fs.stat(filePath, (err, stats) => {
if (err) {
console.error('Error stating file:', err);
return;
}
if (stats.isDirectory()) {
if (file === '.git') {
console.log('Deleting .git directory:', filePath);
fs.rmdir(filePath, { recursive: true }, err => {
if (err) {
console.error('Error deleting .git directory:', err);
} else {
console.log('.git directory deleted successfully:', filePath);
}
});
} else {
deleteGitFolders(filePath); // 递归调用,进入下一级目录
}
}
});
});
});
}
const startDirectory = './';
deleteGitFolders(startDirectory);