clean.mjs 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. import { promises as fs } from 'node:fs';
  2. import { join, normalize } from 'node:path';
  3. const rootDir = process.cwd();
  4. /**
  5. * 递归查找并删除目标目录
  6. * @param {string} currentDir - 当前遍历的目录路径
  7. * @param {string[]} targets - 要删除的目标列表
  8. */
  9. async function cleanTargetsRecursively(currentDir, targets) {
  10. const items = await fs.readdir(currentDir);
  11. for (const item of items) {
  12. try {
  13. const itemPath = normalize(join(currentDir, item));
  14. const stat = await fs.lstat(itemPath);
  15. if (targets.includes(item)) {
  16. // 匹配到目标目录或文件时直接删除
  17. await fs.rm(itemPath, { force: true, recursive: true });
  18. console.log(`Deleted: ${itemPath}`);
  19. } else if (stat.isDirectory()) {
  20. // 只对目录进行递归处理
  21. await cleanTargetsRecursively(itemPath, targets);
  22. }
  23. } catch (error) {
  24. console.error(
  25. `Error handling item ${item} in ${currentDir}: ${error.message}`,
  26. );
  27. }
  28. }
  29. }
  30. (async function startCleanup() {
  31. // 要删除的目录及文件名称
  32. const targets = ['node_modules', 'dist', '.turbo', 'dist.zip'];
  33. const deleteLockFile = process.argv.includes('--del-lock');
  34. const cleanupTargets = [...targets];
  35. if (deleteLockFile) {
  36. cleanupTargets.push('pnpm-lock.yaml');
  37. }
  38. console.log(
  39. `Starting cleanup of targets: ${cleanupTargets.join(', ')} from root: ${rootDir}`,
  40. );
  41. try {
  42. await cleanTargetsRecursively(rootDir, cleanupTargets);
  43. console.log('Cleanup process completed successfully.');
  44. } catch (error) {
  45. console.error(`Unexpected error during cleanup: ${error.message}`);
  46. process.exit(1);
  47. }
  48. })();