Using bash to clean up node_modules

Once in a while, we work on projects that use external libraries that may need to be stored on our PC's disks locally.
This is almost always the case with projects that use Node.js under the hood. There are these things called "node modules". Apparently, they take up disk space. Once done with, say, your toy project/a lab of some sort, you often need to delete unnecessary junk to save disk space.

Doing this on many projects is tedious and thus automation needs to be made use of. Here is how you can do this with 'bash' on a unix system.

1. In the top direcory that holds your projects, create the bash file

$ touch rm_node_modules.sh

2. Make the script executable

$ chmod a+x rm_node_modules.sh

3. Run the script

$ ./rm_node_modules.sh

4. Building out the command:

  1. From the current directory, find directories with 'node_modules' anywhere in their names

    find . -type d -name "*node_modules*"

  2. To avoid deleting node_modules that may be in other sub directories, limit the operation to 2 levels of directory hierachy

    -maxdepth 2

  3. In case any errors (like 'permissioin denied', etc.) are encountered, just send them to the 'blue nowhere' and don't show them in the console

    -print 2>/dev/null

  4. Now delete any found directories without needing user interaction

    -exec rm -rf {} \

The end result is this command:

find . -type d -name "*node_modules*" -maxdepth 2 -print 2>/dev/null -exec rm -rf {} \;



Here is the final snippet in a gist on Github.