A Node.js script that finds and removes every node_modules folder under a root directory to free disk space. No external dependencies.
You have a root folder (e.g. code/) that contains many projects, each in its own subfolder. Every project has a node_modules directory, which can use a lot of disk space. Running this script from the root folder (or by passing the root path) will recursively find and delete all node_modules directories under it, so you can reclaim space and reinstall dependencies later with npm install in each project when needed.
Example: A code/ folder with 20 projects, each with its own node_modules — run the script once from code/ to remove all 20 (or more, if any project has nested node_modules).
- Recursively scans from a root path and removes every
node_modulesfolder - Dry-run mode (
--dry-run) — lists what would be removed without deleting - Skips symlinks to avoid infinite loops
- Does not delete the script’s own
node_modules(the one in this project) - No npm dependencies — uses only Node.js built-in
fsandpath
- Node.js (v14 or later recommended, for
fs.rmSyncwithrecursive)
If you want to clean all projects under a folder, cd into that folder and run the script by path:
cd /path/to/code
node /path/to/remove-node-module/remove-node-modules.jsThis uses the current directory as the root and removes every node_modules under it.
You can pass the root folder as the first argument from anywhere:
node /path/to/remove-node-module/remove-node-modules.js /path/to/codeTo see which folders would be removed without deleting anything:
node remove-node-modules.js /path/to/code --dry-runThen run without --dry-run to actually delete.
From the project directory:
cd /path/to/remove-node-module
node remove-node-modules.js /path/to/code
# or use current directory
node remove-node-modules.js .| Option / Argument | Description |
|---|---|
| (first argument) | Root directory to scan. Default: current working directory (process.cwd()). |
--dry-run |
Only list node_modules paths that would be removed; do not delete. |
- The script never deletes the
node_modulesfolder inside this project (where the script lives). - After running, restore dependencies in any project with
npm install(oryarn/pnpm) when you need to work on it again.