Remove All node_modules Directories at Once
March 15, 2021 • 2 min read
Here’s my one-liner to delete all the JavaScript dependencies of a repo in a flash.
THE PROBLEM
You want to do a backup of all your current files because you’re switching computers.
Some of your local repositories have unpublished branches so you want to copy them over to your new machine rather than checking out their remote versions.
However, the gazillion files inside node_modules make copying the repo take 2 hours. You don’t want to go on every directory and delete the folder manually.
What do you do?
A SOLUTION
We are going to use Unix's find to look for node_modules folders in our repositories directory, and then we are going to use xargs to pass these paths to rm.
- Go into your repositories directory:
cd my-repos
- List the
node_modulesdirectories you are going to remove:
find . -type d -name node_modules
# ./example-repo/node_modules
# ./example-repo/node_modules/node-libs-browser/node_modules
# ...
- Let’s use
xargsto pass these paths torm:
find . -type d -name node_modules | xargs rm -rf
- Done! let’s double-check that all the
node_moduleshave been deleted:
find . -type d -name node_modules
# Empty
Now copying over our repositories directory to our new machine takes just a second, and we can run npm install to generate a new node_modules directory.