Description
Shell command to recursively find and delete all node_modules
directories (or any other directory) from the current directory tree. This is
useful for reclaiming disk space or ensuring a clean state before reinstalling dependencies.
Beyond just node_modules
, this same pattern can be used to clean other build artifacts and cache directories in
monorepos like .turbo
, dist
, .swc
, .next
, and coverage
directories, giving you a true “clean start” for your projects.
Code Byte
# Remove all node_modules directories
find . -name "node_modules" -type d -prune -exec rm -rf {} \; -print
# Silent version (no output)
find . -name "node_modules" -type d -prune -exec rm -rf {} +
# Monorepo clean start - remove all build artifacts
find . \( -name "node_modules" -o -name ".turbo" -o -name "dist" -o -name ".swc" -o -name ".next" -o -name "coverage" \) -type d -prune -exec rm -rf {} \; -print
Example usage:
# Remove all node_modules in current directory tree
find . -name "node_modules" -type d -prune -exec rm -rf {} \; -print
# Dry run - see what would be deleted without removing
find . -name "node_modules" -type d -prune
# Check disk space saved
du -sh . && find . -name "node_modules" -type d -prune -exec rm -rf {} + && du -sh .
# Remove specific directories in monorepos
find . -name ".turbo" -type d -prune -exec rm -rf {} + # Turborepo cache
find . -name "dist" -type d -prune -exec rm -rf {} + # Build outputs
find . -name ".next" -type d -prune -exec rm -rf {} + # Next.js cache
find . -name "coverage" -type d -prune -exec rm -rf {} + # Test coverage
# Create an alias for quick access
alias clean-node='find . -name "node_modules" -type d -prune -exec rm -rf {} \; -print'
alias clean-mono='find . \( -name "node_modules" -o -name ".turbo" -o -name "dist" -o -name ".swc" -o -name ".next" -o -name "coverage" \) -type d -prune -exec rm -rf {} \; -print'
Why This Works
-name "node_modules"
- Match directories with this exact name-type d
- Only match directories-prune
- Don’t descend into matched directories (more efficient)-exec rm -rf {} \;
- Execute removal on each found directory-print
- Show what’s being removed
This approach avoids the “argument list too long” error that occurs with glob patterns when there are many matches.