If you’re a NodeJS dev, you surely know the node_modules folder, right? It’s like a cosmic “black hole”, with infinite “weight”. Even a tiny demo project eats 50MB - 200MB. If you work on a lot of projects, or clone a bunch of NodeJS repos to your machine and install them, there go a few dozen GB of your drive, guaranteed.
The cleanup solution is very simple: Nuke everything. Whenever you need to work on a project again, go in and npm install later. Oh, and once you’ve cleaned up, switch to pnpm to keep things “light”. Why it’s “light” is a story for another post.
Here are the steps to free up space on your machine.
1. Check the size first
You should run this first to check that the command finds the right files and to see how much disk space you’re wasting.
Move into the root folder that holds your source code (e.g. cd ~/Projects or cd D:\DevWork), then run:
Mac / Linux:
Find all node_modules folders and total up their size:
1 | find . -name "node_modules" -type d -prune -print | xargs du -chs |
Windows:
1 | FOR /d /r . %d in (node_modules) DO @IF EXIST "%d" echo %d |
2. Wipe them out
Once you’ve confirmed the list from step 1 looks okay, run this command to delete.
A small heads-up: once this runs, everything is gone for good, no undo. Double-check which folder you’re standing in (with the pwd command) before hitting Enter.
Mac / Linux:
1 | find . -name 'node_modules' -type d -prune -print -exec rm -rf '{}' \; |
Windows:
If you’re using cmder or the git bash cli
1 | FOR /d /r . %d in (node_modules) DO @IF EXIST "%d" rm -rf "%d" |
Windows (CMD):
Note: This command uses rm -rf (if you have Git Bash/Tools installed) or you have to change it to rd /s /q if you’re on plain CMD.
1 | FOR /d /r . %d in (node_modules) DO @IF EXIST "%d" rd /s /q "%d" |
Congrats, you’ve just taken down a “black hole”.