-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathremove-node-modules.js
More file actions
90 lines (72 loc) · 2.41 KB
/
Copy pathremove-node-modules.js
File metadata and controls
90 lines (72 loc) · 2.41 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#!/usr/bin/env node
import fs from "fs";
import path from "path";
import { fileURLToPath } from "url";
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
// Parse CLI: root path (first non-flag arg) or cwd, --dry-run flag
const args = process.argv.slice(2);
const dryRun = args.includes("--dry-run");
const rootArg = args.find((a) => !a.startsWith("-"));
const rootPath = rootArg ? path.resolve(process.cwd(), rootArg) : process.cwd();
// Directories we skip when recursing (don't descend into them)
const SKIP_DIRS = new Set(["node_modules", ".git"]);
function findAndRemoveNodeModules(root, dryRunMode) {
let count = 0;
if (!fs.existsSync(root)) {
console.error(`Error: Path does not exist: ${root}`);
process.exit(1);
}
const stat = fs.statSync(root);
if (!stat.isDirectory()) {
console.error(`Error: Not a directory: ${root}`);
process.exit(1);
}
let entries;
try {
entries = fs.readdirSync(root, { withFileTypes: true });
} catch (err) {
console.error(`Error reading ${root}:`, err.message);
return count;
}
for (const ent of entries) {
if (!ent.isDirectory()) continue;
const fullPath = path.join(root, ent.name);
// Do not follow symlinks (avoid loops)
let entStat;
try {
entStat = fs.statSync(fullPath);
} catch {
continue;
}
if (entStat.isSymbolicLink()) continue;
if (ent.name === "node_modules") {
// Skip deleting node_modules in the script's own project
const scriptOwnNodeModules = path.join(__dirname, "node_modules");
if (path.resolve(fullPath) === path.resolve(scriptOwnNodeModules)) {
continue;
}
if (dryRunMode) {
console.log(`[dry-run] Would remove: ${fullPath}`);
} else {
try {
fs.rmSync(fullPath, { recursive: true, force: true });
console.log(`Removed: ${fullPath}`);
} catch (err) {
console.error(`Failed to remove ${fullPath}:`, err.message);
}
}
count++;
continue;
}
if (SKIP_DIRS.has(ent.name)) continue;
count += findAndRemoveNodeModules(fullPath, dryRunMode);
}
return count;
}
const total = findAndRemoveNodeModules(rootPath, dryRun);
if (dryRun) {
console.log(`\n[dry-run] Would remove ${total} node_modules folder(s). Run without --dry-run to delete.`);
} else {
console.log(`\nDone. Removed ${total} node_modules folder(s).`);
}