I quickly understood that I had forgotten to remove node_modules when I wanted to copy my projects folder to a new computer and the process was going to take multiple hours. Luckily, my dotfiles already contained a command to remove all the node_modules folders at once. This time the command saved me ~40 GB.
# Use the command at you own risk
find . -name "node_modules" -type d -prune -exec rm -rf '{}' +
There's a lot to the command, but here's an explanation of each part to demystify it.
- 
find- A command that comes built-in with MacOS and Linux.
- 
.- Look from this location
- 
-name "node_modules"- Make sure the last component of the pathname matchesnode_modules
- 
-type d- We are looking for a directory (d)
- 
-prune- Stopsfindfrom descending into the folder, meaning that it won't look fornode_modulesinsidenode_modulesand so on.
- 
-exec rm -rf '{}' +- Runs the specified command,rm, with flagsr(remove directory) andf(do not ask for confirmation no matter what the file permissions are).'{}'will be replaced by the pathname that's been found.+means thatfindwill append all the file paths to a single command instead of runningrmfor each.
If you just want to find node_modules folders and display their disk size use the following command.
find . -name "node_modules" -type d -prune -print | xargs du -chs
There's also an
npmcommand that you can use by runningnpx npkillif you don't want to mess with terminal commands.
 

 
    
Top comments (0)