How to check how much space node_modules folders take up

You have probably seen the meme about node_modules being the heaviest objects in the universe. While that is an exaggeration in the service of a joke, your project’s node dependencies can gobble a considerable chunk of your hard-drive. How can you find out how much space your node_modules folders take up?

node_modules meme comparing node_modules to sun, neutron star, and black hole as the heaviest objects in the universe. node_modules is number 1!

Command to check the size of the node modules on your system

You can find out how much space is being used on your system by running the following command on your home directory:

Shell
find . -type d -iname node_modules -prune  | sed 's/^/"/g' | sed 's/$/"/g' | tr '\n' ' ' | xargs du -chs

This command requires the common unix utility programs: find, sed, tr, xargs, and du that are installed by default on most unix-like systems (linux and co). This command accommodates for filepaths with spaces, I noticed that the command used in other articles will choke on these filepaths!

This is the abbreviated output from the command on my system:

terminal

find . -type d -iname node_modules -prune | sed 's/^/"/g' | sed 's/$/"/g' | tr '\n' ' ' | xargs du -chs
59M ./programming/study/css/css-grid/css-grid-master/node_modules
21M ./programming/workspace/articles/scroll-direction/node_modules
29M ./programming/workspace/articles/trignometry/node_modules
22M ./programming/workspace/articles/stranger-things/node_modules
… …
9.0G total

It is 9 gigabytes for me!

How do I free this space up?

How you liberate the disk space is up to you!

Some people like to nuke every node_modules folder on their system. Then when they need to work on a project, they have to reinstall the dependencies. You can do a recursive find and delete using the rm command with find, but be careful! You can read the article, How to Delete ALL node_modules folders on your machine, if you want to do that.

If you are on Windows, keep in mind that it can be particularly slow! You may encounter the error below:

The source file name(s) are larger than is supported by the file system. Try moving to a location which has a shorter path name, or try renaming to shorter name(s) before attempting this operation

You can read this article to find the quickest option: Quick way to delete node_modules folder on Windows.

I prefer to do this as part of general tidy up of my projects. Over time, I have migrated some of my projects to use pnpm instead of npm, and that has reduced the footprint of my projects significantly. I am trying to improve my habits with deleting projects that I downloaded temporarily. It is a bit of a battle to curb the tide in JavaScript-land!

Tagged