How to remove all the node_modules folders content
By Flavio Copes
Learn how to bulk remove every node_modules folder with a single find command, freeing up gigabytes of disk space across all your old Node.js projects.
You can remove every node_modules folder inside a directory tree with a single command:
find . -name "node_modules" -type d -prune -exec rm -rf '{}' +
Run it from the parent folder that contains all your projects. Every node_modules folder inside it, at any depth, gets deleted.
Let me tell you why I needed this, and how the command works.
Why delete node_modules folders?
I had to transfer a folder full of old projects to a new computer, and after trying to compress it, I realized the size was 8GB. A bit too much for some coding projects that only contain text files.
They were all JavaScript projects, and every project contained a node_modules folder.
The folder is totally unnecessary because I can always run npm install in a project to re-generate it. And most of those projects were old things I’ll never touch again.
So I went into the parent folder, which I called dev, ran the command above, and the folder went from 8GB to 2GB. Pretty nice for a one-line command.
How does the command work?
find . searches the current folder and everything inside it.
-name "node_modules" -type d matches only directories with that exact name.
-prune tells find to stop descending once it finds a match. Packages often have their own node_modules folder nested inside, and without -prune the command would try to delete folders that are already inside a folder being deleted.
-exec rm -rf '{}' + runs rm -rf on the results. The + at the end passes many folders to a single rm call, instead of starting one process per folder.
Check before you delete
rm -rf does not ask for confirmation. Before running the full command, run just the find part to see the list of folders it would remove:
find . -name "node_modules" -type d -prune
You can also see how much space each one takes, by swapping rm -rf with du -sh:
find . -name "node_modules" -type d -prune -exec du -sh '{}' +
1.2G ./old-blog/node_modules
890M ./twitter-clone/node_modules
One thing to watch out for
The command starts from the folder you run it in. Run it in the wrong place, like your home folder, and it also wipes node_modules from projects you’re actively working on. Nothing is lost forever, npm install brings everything back, but reinstalling a few big projects takes time.
So always cd into the right parent folder first, and run the dry-run version before the real one.
I originally found this command on this blog.
Related posts about js: