If you do any kind of front end development or front end development training, you have probably accumulated a bunch of projects with aging/stale “node_modules” directories. Are you going to take time to open every single old project you have to nuke the node_modules directory? Nobody has time for that.
I wanted to migrate a bunch of old code to an archive drive and because of the size of each “node_modules” directory, I didn’t care to save “node_modules” archives with my old projects (especially since I can just run npm install
to reinstall if needed).
Clear all node_modules Directories | Mac and Linux
Since I don’t have any control over how individual users use, input, modify or copy/paste the node_modules nuke command, it is only reasonable that I mention that I take zero responsibility for the outcomes of the use, misuse, etc… you get the picture.
TL;DR: I saved about 5GB after running this command:
- Open your terminal.
- Browse to your master project directory or the top level of where you have a bunch of projects stored.
- Run the command:
find . -name "node_modules" -type d -prune -exec rm -rf '{}' +
How it works
Since this blog is driven towards educating about the process of solving problems versus just providing blind answers, lets take some time to break this command down into pieces to examine how it works.
find .
Instructs the find program to search for files in the current directory.
.-name "node_modules"
Instructs the find program to search for files named “node_modules”.-type d
Instructs the find program to only look for file directories named “node_modules”.-prune
Instructs the find program to not descend into the current file/directory for it to exclude child “node_modules” directories. On Mac, since -d was specified, -prune has no effect on the find program’s lookup results (per the man pages). However, on Linux, -prune still instructs the find program to not descend into the current file/directory.-exec rm -rf '{}' +
Instructs the find program to executerm -rf
on the matching results. The code'{}' +
instructs the command line to be built by appending each selected file name at the end thus invoking therm -rf
command less times than the total number of “node_modules” directory matches. This helps with performance.
And there you have it. As I mentioned above, I saved ~5GB by running this command. If you have a lot of projects, you could easily clear up more than ~5GB.
ahmedmhashem says
Thanks, cool one 😉
Tim Ross says
Thanks, that’s a pretty useful trick. Saved me a ton of space from my old projects.
Qaisar Irfan says
Saved 10+ GB 🙂
jusopi says
Is there anyway to have it print out the results of what it finds? Basically to provide some sort of visual feedback that it is indeed working? I have about 16GB of node_modules getting nixed and it’s just sitting there at the moment.