clean.mjs 1.5 KB

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