Skip to content

Instantly share code, notes, and snippets.

@flockonus
Created December 27, 2024 08:03
Show Gist options
  • Save flockonus/c93ca68da7ee04f3fe9f6e39685e84c3 to your computer and use it in GitHub Desktop.
Save flockonus/c93ca68da7ee04f3fe9f6e39685e84c3 to your computer and use it in GitHub Desktop.
const fs = require('fs').promises;
const path = require('path');
async function getFolderSize(folderPath) {
let totalSize = 0;
async function calculateSize(currentPath) {
const files = await fs.readdir(currentPath, { withFileTypes: true });
for (const file of files) {
const filePath = path.join(currentPath, file.name);
if (file.isDirectory()) {
await calculateSize(filePath);
} else {
const stats = await fs.stat(filePath);
totalSize += stats.size;
}
}
}
await calculateSize(folderPath);
return totalSize / (1024 * 1024); // Convert to MB
}
async function findNodeModules(startPath) {
const results = [];
const queue = [startPath];
const seen = new Set();
while (queue.length > 0) {
const currentPath = queue.shift();
try {
const files = await fs.readdir(currentPath, { withFileTypes: true });
for (const file of files) {
if (file.isDirectory()) {
const fullPath = path.join(currentPath, file.name);
// Skip if we've already seen this path
if (seen.has(fullPath)) continue;
seen.add(fullPath);
if (file.name === 'node_modules') {
const size = await getFolderSize(fullPath);
results.push({
path: fullPath,
size: size.toFixed(2)
});
// Don't add this path to the queue - stop searching this branch
} else {
queue.push(fullPath);
}
}
}
} catch (error) {
console.error(`Error accessing ${currentPath}: ${error.message}`);
}
}
return results;
}
// Example usage
async function main() {
const searchPath = process.argv[2] || '.';
try {
console.log(`Searching for node_modules folders in: ${searchPath}`);
const nodeModules = await findNodeModules(searchPath);
if (nodeModules.length === 0) {
console.log('No node_modules folders found.');
return;
}
// Sort by size (largest first)
nodeModules.sort((a, b) => parseFloat(b.size) - parseFloat(a.size));
console.log('\nFound node_modules folders (sorted by size):');
nodeModules.forEach(({ path: folderPath, size }) => {
console.log(`\nPath: ${folderPath}`);
console.log(`Size: ${size} MB`);
});
// Filter folders larger than 30MB and create removal commands
const largerThan30MB = nodeModules.filter(folder => parseFloat(folder.size) > 30);
if (largerThan30MB.length > 0) {
console.log('\n\nRemoval commands for folders larger than 30MB:');
console.log('# Copy and paste these commands to remove the folders');
console.log('# WARNING: Make sure you want to delete these folders!\n');
largerThan30MB.forEach(({ path: folderPath }) => {
console.log(`rm -r "${folderPath}"`);
});
}
} catch (error) {
console.error('Error:', error.message);
}
}
main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment