Remove node_modules from all folders

A cross-platform guide to reclaiming disk space from stray node_modules folders

Velu S Gautam1 min readLearnings

If you work across multiple JavaScript projects, node_modules folders pile up fast and quietly eat disk space. Below are a few ways to check how much space they're using, and several ways to remove them on macOS/Linux, Windows, or via a cross-platform Node.js script.


1. Check how much space node_modules is using (macOS/Linux)

BASH
cd projects
find . -name "node_modules" -type d -prune | xargs du -chs

Sample output:

TEXT
 28M  ./image-resize/node_modules
 14M  ./backend/node_modules
217M  ./hectane-next/node_modules
259M  total

This finds every node_modules directory without descending into them (-prune), then totals their sizes.


2. Node.js way (cross-platform, with granular control)

JAVASCRIPT
const fs = require('fs');
const path = require('path');
 
function removeNodeModules(base) {
  const entries = fs.readdirSync(base, { withFileTypes: true });
 
  for (const entry of entries) {
    if (!entry.isDirectory()) continue;
 
    const fullPath = path.join(base, entry.name);
 
    if (entry.name === 'node_modules') {
      fs.rmSync(fullPath, { recursive: true, force: true });
      console.log(`${fullPath} deleted!`);
    } else {
      removeNodeModules(fullPath);
    }
  }
}
 
removeNodeModules('.');

Save this as remove_node_modules.js in the parent folder, then run:

BASH
node remove_node_modules.js

This walks every subdirectory and deletes any folder named node_modules it finds, without recursing into deleted folders.

Requirements: Node.js 14.14 or later. This uses fs.rmSync, which replaces the older fs.rmdir(path, { recursive: true }, callback) pattern — that form is deprecated and no longer works in current Node releases.

Note: Use this method when you need finer control — for example, to skip specific folders by adding a condition inside the loop before deletion.


3. macOS / Linux one-liner

BASH
cd projects
find . -name "node_modules" -type d -prune -exec rm -rf '{}' +

Same idea as the disk-usage check above, but deletes each match instead of measuring it.


4. Windows

Command Prompt — run directly at the prompt (not saved as a .bat file):

CMD
FOR /d /r . %d in (node_modules) DO @IF EXIST "%d" rd /s /q "%d"

If you save this inside a .bat script, double every % (%%d instead of %d) — that's a batch-file requirement, not a Command Prompt one. Note also that rd /s /q is the correct Windows deletion command; rm -rf doesn't exist in cmd.exe.

PowerShell (more reliable output and error handling):

POWERSHELL
Get-ChildItem -Path . -Include node_modules -Recurse -Force | Remove-Item -Recurse -Force

Bonus: use a dedicated tool

If you'd rather not script this yourself, npkill is an interactive CLI that scans your disk, shows every node_modules folder with its size, and lets you select which ones to delete:

BASH
npx npkill

Comments