til / Delete unused node_modules
After developing on a computer for a while you’ll probably end up with a bunch of projects. If those projects are JavaScript there’s a good change that they contain a node_modules directory. From time to time it’s a good idea to remove all of these folders, since they can get quite big, and re-download the dependencies in the projects you’re actively using.
I have aliased the following command to node-prune and have been using it a couple of years without any issues. When I last ran the command on I got back ~40 GB of disk space. Use it at your own risk.
alias node-prune='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 only want to find and display the size of the folders you can use the following command
find . -name "node_modules" -type d -prune -print | xargs du -chs
There’s also npkill which looks up and displays node_modules, displays their size and allows you to delete the folders. Run it by using npx npkill.