Cleanup Node Modules recursively

A common situation in learning modern WebDevelopment workflow is the constant accumulation of projects with aging/stale “node modules” directories.

The node_modules folder is where your project dependencies are stored, common knowledge. Its weight is also common knowledge and most of the time is HUGE

NPM modules hole

AKA Search&Destroy, but search first…

find . -name 'node_modules' -type d -prune

To clear all node_modules folders from current folder recursively:

This probably what you need to use

find . -name "node_modules" -type d -prune -exec rm -vrf '{}' +

To ignore a specific subfolder:

In case you need something customized

find . -name "node_modules" -type d -prune -not -path "./folder-to-ignore/node_modules" -exec rm -vrf '{}' +

ELI5

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 execute rm -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 the rm -rf command less times than the total number of “node_modules” directory matches. This helps with performance.

This can save you some GB over several projects. If you need the node modules back, you can simply run npm install again

Bonus: use RimRaf

Install RimRaf node util: ] npm install rimraf -g

And in the project folder delete the node_modules folder with:

rimraf node_modules