Petros Kyriakoupersonal blog

I am a full stack web developer. Love tinkering all the time, especially anything javascript related.

How to remove all node_modules folders in your system

December 15, 2019

If you have worked with node for a while and created a few projects you might find soon enough that nodemodules can take quite some space. Its like a bottomless pit when it comes to nodemodules and there is duplication upon duplication of node modules because of the nature of how npm works.

Note: The method below only works on Linux and MacOS

Cleanup

So, at times you might need to free space from projects that you don't use much now and you forgot to delete the node_modules folder.

Command

find . | grep /node_modules$ | grep -v /node_modules/ | xargs rm -fR

What this will do, is execute a find command in the current directory (where . means current directory), grab all folders named node_modules and execute rm -fR to remove them.

So you could think that by navigating to your root directory and executing this script you can safely remove all folders named node_modules.

Second option

As pointed out by ConfusedChihuahua, a reddit user it might be safer to use a command without regular expressions which you can find below.

find -type d -and -name node_modules -and - exec rm -rf {} ;

Beware that if any installed applications use node_modules they will stop working so be careful in which directory you are running any of the two commands above.

My recommendation is only to use this script in a folder that contains your projects. This way you have control over what is deleted.

Making it a script

If you want to have it as a script somewhere

touch clean.sh

Open file using nano or your favorite editor and paste the content

#!/bin/bash

find . | grep /node_modules$ | grep -v /node_modules/ | xargs rm -fR

Make file executable

chmod +x clean.sh

Run script

./clean.sh # remember it removes everything in the current directory and below

Conclusion

This script helped me free up to 10gb of node_modules. Just be careful to only remove node_modules in a confined directory and not Operating-System wide.