-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathclean-node-modules.js
67 lines (58 loc) · 1.87 KB
/
clean-node-modules.js
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
import * as fs from "node:fs/promises";
import path from "node:path";
import { fileURLToPath } from "node:url";
/**
* Walk all of the workspace directories and `rm -rf` the top-level
* `node_modules` directories.
*/
async function cleanNodeModules() {
const workspaces = await getWorkspaces();
// Get all the node_modules directories in each workspace
const nodeModulesByWorkspace = await Promise.all(
workspaces.map(async (workspace) => {
const files = await fs.readdir(workspace, { withFileTypes: true });
return files
.filter((dirent) => dirent.isDirectory())
.map((dirent) => path.join(workspace, dirent.name, "node_modules"));
}),
);
const allNodeModulePaths = ["node_modules"]
.concat(nodeModulesByWorkspace.flat())
.sort();
// Remove each node_modules directory
await Promise.all(
allNodeModulePaths.map(async (nodeModulePath) => {
try {
await fs.rm(relativePath(nodeModulePath), {
recursive: true,
force: true,
});
console.log(`Removed ${nodeModulePath}`);
} catch (error) {
console.error(`Error removing ${nodeModulePath}:`, error);
}
}),
);
}
await void cleanNodeModules();
/**
* Get the list of top-level directories in the workspace
*/
async function getWorkspaces() {
const filepath = relativePath("pnpm-workspace.yaml");
const data = await fs.readFile(filepath, "utf8");
// Extract directory names using regex
const lines = data.split("\n"); // Split the content into lines
const directories = lines
.map((line) => line.trim()) // Remove leading/trailing whitespace
.filter((line) => line.startsWith("-")) // Only keep lines that start with `-`
.map((line) => line.replace(/^- "?(.+?)\/\*"?.*$/, "$1"));
return directories;
}
/**
* @param {...string} parts
*/
function relativePath(...parts) {
const __dirname = fileURLToPath(new URL(".", import.meta.url));
return path.resolve(__dirname, ...parts);
}