A developer trying to support all of the node_modules on his back

Removing node_modules under a folder

2 min read.

This quick article explains how to clean up all dependencies installed with npm or yarn, and stored in folders called “node_modules” within your project and solution files. This regrettable step might be required to either free some disk space or clear weirdly broken dependencies from your project(s). Hope this will be as helpful to you as it’s been to me 🙄

Background

npm and yarn install all dependencies, and dependencies of dependencies, and dependencies of those dependencies of dependencies, and so on, in a folder called node_modules. If you have a bunch of projects in your solution, each will have a completely isolated and independent node_modules folder on its own.

These folders can take hundreds and hundreds of megabytes per project – and npm might not always be great at managing the file versions in those directories.

So long story short, even if you don’t have to free some disk space, you might occasionally need to remove the node_modules folders.

Anyway – let’s get to it, then!

Solution

PowerShell is, well, a very powerful shell, but starting with what I thought would be the most obvious commandlet, Remove-Item, I couldn’t easily figure out a way to recursively and silently remove all folders called node_modules within a file structure.

But with PowerShell, there’s always another way to achieve your goals!

Instead of running Remove-Item -Filter -Recurse with increasingly obscure filters (or multiple different \*\*\node_modules\ -patterns), you can just fetch all node_modules directories with Get-ChildItem and then proceed to remove them one-by-one.

I don’t think it’s as fast as Remove-Item would be, but you’ll probably get there this way too.

cd C:/code/
$nodemodules = Get-ChildItem "node_modules" -Recurse -Force -Attributes "Directory"
$nodemodules.Count # For good measure
$nodemodules | Remove-Item -Recurse

If you want to first run the removal without, well, actually removing anything, you can replace the last line with this instead:

$nodemodules | Remove-Item -Recurse -WhatIf

Et voilà! You should be good with this.

mm
0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments