
cleaninstall-node
io.github.ahusan/cleaninstall-node
Diagnose and fix broken Node.js/Deno installs instead of rm -rf node_modules and the lockfile
Documentation
CleanInstall Node
Stop deleting node_modules blindly. cleaninstall-node finds out why an install is broken and applies the smallest fix, warns you right after a git pull changes your dependencies, and cleans safely when you really do want a fresh start. Works with npm, pnpm, yarn, bun and Deno, in single projects and monorepos.
npx cleaninstall-node doctor # what's wrong? (and --fix to repair it)
npm run dev 2>&1 | npx cleaninstall-node doctor --from-error # explain this error
npx cleaninstall-node hook install # warn after pull/checkout/rebase
npx cleaninstall-node --install # clean + reinstall, safely
Using an AI coding agent? Give it the MCP server so it diagnoses broken installs instead of running rm -rf node_modules package-lock.json:
claude mcp add cleaninstall -- npx -y cleaninstall-node mcp # tools for the agent
npx cleaninstall-node agent install # guidance + a guard hook
Upgrading from 2.x? Lockfiles are now kept unless you pass
--lockfiles, the CLI asks once before deleting (use-yin scripts), and Node.js 20+ is required. See the changelog.
Features
- Removes common clutter (
node_modules, build output, etc.) - Workspace Aware: Automatically detects workspaces defined in
package.jsonorpnpm-workspace.yaml. - Glob Pattern Support: Use glob patterns (e.g.,
*.log,dist-*) in configuration for flexible matching. - Dry Run Mode: See what would be deleted without actually removing anything.
doctor: Diagnoses why an install is broken (stale lockfile, wrong Node, native ABI mismatch, mixed package managers) and applies the smallest fix.doctor --from-error: Paste or pipe an error; get what it means for this project and the fix.- Agent setup:
agent installadds guidance to AGENTS.md / CLAUDE.md and a Claude Code hook that blocksrm -rf node_modulesand lockfile deletion. - MCP server for AI agents: Claude Code, Cursor, VS Code and others can diagnose and fix installs through structured tools.
- Git hook: Warns (or reinstalls) right after a pull, branch switch or rebase changes your dependencies.
- Safe by default: Shows what will be removed and asks once before deleting (skip with
-y). Lockfiles are kept unless you pass--lockfiles. - Interactive Mode: Confirm each deletion individually.
- Auto-Install: Runs
npm,yarn,pnpmorbuninstall after cleanup, detected from thepackageManagerfield or your lockfile. - Configurable via CLI,
package.json, or.cleaninstallnoderc.
Why CleanInstall Node?
Compared to manual deletion or other tools:
- vs
rm -rf node_modules && npm install: Workspace-aware, handles monorepos automatically, safer with dry-run mode - vs
npx rimraf: Built-in monorepo support, auto-reinstall, interactive mode, glob patterns - vs manual deletion: Cross-platform, configurable, preview before deletion, handles multiple workspaces
Quick Start
# Clean and reinstall dependencies in one command
npx cleaninstall-node --install
# Full reset, including lockfiles (resolves fresh dependency versions!)
npx cleaninstall-node --lockfiles --install
# Non-interactive (CI / scripts): skip the confirmation prompt
npx cleaninstall-node -y
# Preview what would be deleted (dry run)
npx cleaninstall-node --dry-run
# Interactive mode - confirm each deletion
npx cleaninstall-node -i
doctor: find out why before you delete
Most "nuke node_modules" moments have a specific cause. doctor finds it and applies the smallest fix that works:
npx cleaninstall-node doctor # diagnose
npx cleaninstall-node doctor --fix # apply the smallest fix
npx cleaninstall-node doctor --json # machine-readable, exit code 1 on errors
𩺠cleaninstall-node doctor ā ~/code/app (npm)
ā node_modules is out of sync with package-lock.json (1 difference)
ms: installed 2.1.3, lockfile 2.1.2
Usually happens after git pull / switching branches without reinstalling.
ā 1 native module was built for a different Node version
better-sqlite3: built for ABI 115, this Node needs 127
ā Node v22.11.0 matches .nvmrc (22)
2 errors, 0 warnings.
Smallest fix (run with --fix to apply):
ā npm install
ā npm rebuild better-sqlite3
| Check | Detects | Fix |
|---|---|---|
| Node version | Running Node vs .nvmrc, .node-version, .tool-versions, volta.node, engines.node | Manual (nvm use). Blocks --fix so nothing is rebuilt for the wrong Node |
| Lockfile sync | node_modules doesn't match the lockfile, e.g. after a git pull (npm, pnpm, yarn v1) | install |
| Direct dependencies | A dependency is missing or installed outside its package.json range (all package managers, workspaces included) | install |
| Native modules | A .node addon was built for another Node ABI, or for another OS/CPU (Docker volume, Rosetta) | rebuild <only those packages> |
| Installer | node_modules was written by a different package manager than the project uses | remove node_modules + install |
| Lockfiles | More than one package manager's lockfile, a mismatch with packageManager, no lockfile at all | Manual |
| pnpm builds | pnpm 10 skipped a package's build scripts (ignoredBuilds) | Manual (pnpm approve-builds) |
| yarn system | yarn v1 installed under a different Node ABI or platform | install |
Native addons are loaded in a separate short-lived process, so a crashing addon can't take doctor down. Skip that check with --no-native.
Paste the error: --from-error
Start from the error you actually got. doctor --from-error explains what it means for this project and folds it into the fix plan:
npm run dev 2>&1 | npx cleaninstall-node doctor --from-error # pipe it in
npx cleaninstall-node doctor --from-error "Cannot find module 'axios'"
npx cleaninstall-node doctor --from-error --fix # and fix it
𩺠cleaninstall-node doctor --from-error ā ~/code/app (npm)
What the error means
ā axios is in package.json but not installed
axios (^1.7.0) is declared, but node_modules doesn't have it: the install is missing or out of date.
In this project
ā 2 dependencies are not installed ā likely related
ā 1 other check passed
Smallest fix (run with --fix to apply):
ā npm install
The same error can need different fixes. Cannot find module 'x' gets a different answer when x is declared but not installed (install it), only present through another package (add it to package.json), installed at the wrong version, a relative import (a code problem, so no reinstall), or a Node built-in. Recognised errors:
| Error | Example | What it suggests |
|---|---|---|
| Native module, wrong Node | NODE_MODULE_VERSION 115 ⦠requires 127 | Rebuild that one package |
| Native module, wrong OS/CPU | invalid ELF header | Rebuild that package, and stop sharing node_modules with Docker |
| Platform binary missing | rollup, esbuild, sharp, swc ā¦-linux-x64 | Clean reinstall |
| Module not found | Node CJS/ESM, Vite, webpack, Next.js, TS2307 | Depends on the project (see above) |
| Command not found | sh: vite: not found, 'tsc' is not recognized | Install, npx, or which package to add |
| ESM-only package | ERR_REQUIRE_ESM | Newer Node, import(), or pin the old major |
| Subpath not exported | ERR_PACKAGE_PATH_NOT_EXPORTED | Check the installed major |
| Lockfile out of sync | npm ci, ERR_PNPM_OUTDATED_LOCKFILE, yarn --frozen-lockfile | Install locally and commit the lockfile |
| Peer conflict | ERESOLVE | Align versions (--legacy-peer-deps only as a last resort) |
| Wrong Node for a dependency | EBADENGINE, yarn/pnpm engine errors | Switch Node (blocks --fix) |
| Wrong package manager | Corepack mismatch, npm on workspace: | Use the declared package manager |
| Broken install | ENOTEMPTY, interrupted installs | Clean reinstall |
| Other | EINTEGRITY, EACCES, disk full vs. file-watcher ENOSPC, gyp ERR! | Specific steps |
With --json, the report includes error.matches for agents and scripts. An error it doesn't recognise still gets the normal doctor checks.
Use it from AI agents (MCP)
When an install breaks, AI coding agents tend to run rm -rf node_modules package-lock.json && npm install. That throws away the lockfile, quietly upgrades dependencies, and often doesn't fix the real cause. cleaninstall-node mcp is a Model Context Protocol server that gives the agent the diagnosis and the smallest fix instead.
It's listed on the official MCP Registry as io.github.ahusan/cleaninstall-node and on Glama.
| Tool | What it does | Changes files |
|---|---|---|
explain_error | Explains an error message for this project (everything --from-error knows) and returns a fix plan | No |
diagnose | Full doctor health check and fix plan | No |
apply_fix | Runs the plan: targeted rebuild, install, or (rarely) a clean reinstall. Never touches lockfiles | Yes |
plan_clean | Lists what a cleanup would delete, with sizes | No |
clean | Deletes exactly what plan_clean listed; can reinstall | Yes |
Built-in safety:
- Plans must be shown first.
apply_fixandcleanonly run with theplan_idfrom a preceding read-only call. If the project changed in between, they refuse and the agent has to re-plan, so it can't delete or install something nobody was shown. - Hard limits. The tools refuse to run on
/, your home folder, or a folder without apackage.json. Lockfiles are only removed when asked, and fixes are blocked while you're on the wrong Node version. - Guidance for the agent. The server's instructions tell it to call
explain_errorbefore deletingnode_modules. - No extra install weight. The server adds no runtime dependencies.
Setup
Claude Code (add --scope project to share it with your team via .mcp.json):
claude mcp add cleaninstall -- npx -y cleaninstall-node mcp
Cursor (.cursor/mcp.json), Windsurf, Claude Desktop (claude_desktop_config.json) and other clients using the mcpServers format:
{
"mcpServers": {
"cleaninstall": { "command": "npx", "args": ["-y", "cleaninstall-node", "mcp"] }
}
}
VS Code (.vscode/mcp.json):
{
"servers": {
"cleaninstall": { "type": "stdio", "command": "npx", "args": ["-y", "cleaninstall-node", "mcp"] }
}
}
Tools default to the folder the client starts the server in, which is normally your project. Every tool also takes a dir argument, and mcp --dir <path> changes the default; use one of these with clients that don't start in a project, such as Claude Desktop. On Windows, if a client can't find npx, use "command": "cmd", "args": ["/c", "npx", "-y", "cleaninstall-node", "mcp"].
Agent setup: agent install
An MCP tool only helps when the agent decides to use it. agent install changes the default:
npx cleaninstall-node agent install # guidance + Claude Code guard hook
npx cleaninstall-node agent install --ask # hook asks you instead of blocking
npx cleaninstall-node agent install --no-hook # guidance only
npx cleaninstall-node agent uninstall
| File | What it gets |
|---|---|
AGENTS.md | A short "diagnose before deleting" section, read by most coding agents |
CLAUDE.md | The same section. If you don't have a CLAUDE.md, it creates one that imports @AGENTS.md, because Claude Code ignores AGENTS.md once a CLAUDE.md exists |
.github/copilot-instructions.md, .cursor/rules/ | The same guidance, only if you already use Copilot instructions or Cursor rules |
.claude/settings.json + .claude/hooks/cleaninstall-guard.js | A Claude Code PreToolUse hook that blocks Bash commands deleting node_modules or a lockfile, and tells the agent what to run instead |
The guard catches rm -rf node_modules (also ./, */, **/ and node_modules/* forms), rimraf, find ⦠-exec rm / -delete / | xargs rm, git clean -x, PowerShell Remove-Item, rd /s, bash -c "ā¦", fs.rmSync(ā¦) one-liners, and any deletion of package-lock.json, yarn.lock, pnpm-lock.yaml or bun.lock(b). It allows targeted cache clears such as rm -rf node_modules/.vite, and commands that only mention these names. The safe alternatives it suggests (npx cleaninstall-node -y --install, --lockfiles when the user asks) aren't blocked, so the agent always has a sanctioned way forward.
Notes:
- The guard script has no dependencies, so it works even when node_modules is missing or broken, and adds about 30 ms (one Node start-up) to each Bash call.
- If anything goes wrong inside the guard, it allows the command rather than block the agent.
- Turn it off for a session with
CLEANINSTALL_GUARD=off. Try it on any command withnpx cleaninstall-node agent check <command>. - Settings are merged: your permissions and other hooks are kept, and an invalid
settings.jsonis left untouched. Everything installed is printed; commit it so your team gets it. - Claude Code runs project hooks without asking each person to approve them. So review the guard script before you commit it.
- Tested in a real headless Claude Code session (Bash allowed): the hook stopped
rm -rf node_modulesand the agent relayed the reason. Behaviour inbypassPermissionsmode is up to Claude Code and isn't verified here.
Git hook: know when to reinstall
You pull, switch branches or rebase, the lockfile changes, nobody reinstalls, and an hour later something fails in a confusing way. The hook catches that moment:
npx cleaninstall-node hook install # warn (default)
npx cleaninstall-node hook install --mode install # run the install / rebuild automatically
npx cleaninstall-node hook uninstall
$ git pull
š¦ cleaninstall-node: dependencies changed (package-lock.json, package.json)
ā node_modules is out of sync with package-lock.json (3 differences)
ā run: npm install
(or: npx cleaninstall-node doctor --fix)
- Runs on
post-checkout(branch switch),post-merge(pull/merge) andpost-rewrite(rebase, reported once at the end). - Fast: it first checks which files changed. Unless a lockfile,
package.json,pnpm-workspace.yaml,.nvmrc/.node-version,.npmrcor.yarnrc.ymlchanged, it exits immediately. When one did, it runsdoctor's checks and stays silent ifnode_modulesalready matches. - Safe:
--mode installonly ever runs an install or a targeted rebuild. It never deletesnode_modules, and does nothing when you're on the wrong Node version. A hook can't fail your git command. - Plays well with others: if husky manages your hooks, the hook goes into
.husky/so you can commit it for the whole team. Existing hook scripts are kept, and only a marked block is added or removed. - Skipped when
CIis set. Skip once withCLEANINSTALL_SKIP_HOOK=1 git pull; override the mode per shell withCLEANINSTALL_HOOK_MODE=warn|install.
To give every teammate the hook without husky, add it to prepare (this needs cleaninstall-node in devDependencies):
{ "scripts": { "prepare": "cleaninstall-node hook install" } }
Deno
Run it with Deno. Grant only what each command needs rather than -A:
# Read-only diagnosis (native modules are skipped without --allow-run)
deno run --allow-read --allow-env npm:cleaninstall-node doctor
# Everything: --fix, cleanup, --install, the MCP server, the git hook
deno run --allow-read --allow-env --allow-write --allow-run=node,deno,npm,pnpm,yarn,bun,git npm:cleaninstall-node doctor --fix
# Global install with the same permissions
deno install -g --allow-read --allow-env --allow-write --allow-run=node,deno,npm,pnpm,yarn,bun,git --name cleaninstall-node npm:cleaninstall-node
| Command | Permissions |
|---|---|
doctor, doctor --from-error, cleanup --dry-run | --allow-read --allow-env |
doctor checking native modules | add --allow-run (it loads each addon with node or deno) |
doctor --fix | --allow-read --allow-env --allow-write --allow-run |
| cleanup | --allow-read --allow-env --allow-write (add --allow-run for --install) |
mcp | --allow-read --allow-env for diagnosis tools; add --allow-write --allow-run for apply_fix / clean |
agent install | --allow-read --allow-env --allow-write |
hook install / the hooks themselves | --allow-read --allow-env --allow-write --allow-run=git (add your package manager for --mode install) |
--allow-run can name exactly the programs: --allow-run=node,deno,npm,pnpm,yarn,bun,git. The programs it starts (e.g. npm install) run outside Deno's sandbox, which is how Deno treats any subprocess. If a permission is missing, the tool says so: a skipped native-module check is reported as skipped, and a cleanup that can't delete exits with code 1 and tells you to add --allow-write.
Deno 2.9+ won't install npm versions published in the last 24 hours. If you need a release from today, add --minimum-dependency-age=0.
Deno projects (deno.lock, deno.json/deno.jsonc, or a package.json installed with deno install) are recognised, and fixes use deno install:
- Lockfile: checks
node_modulesagainstdeno.lock, e.g. after agit pull(Deno stores packages innode_modules/.deno). Optional binaries for other platforms are skipped. deno.jsonimports:npm:imports are checked against what's installed.- Install scripts: says which packages Deno didn't run install scripts for, with the exact
deno install --allow-scripts=npm:ā¦command. - Native modules: loaded with Deno, so you get Deno's verdict. Addons built with the legacy (non-Node-API) API are reported as unsupported by Deno, which a rebuild won't fix. A native module built for another OS or CPU is rebuilt the Deno way: only that package's folder in
node_modules/.denois removed, thendeno install --allow-scripts=ā¦runs. - Global cache:
deno.json-only projects withoutnodeModulesDirkeep npm packages in Deno's global cache, and doctor says there's nothing to check instead of reporting "not installed". - Deno-native projects (JSR, workspaces):
deno.lockvsdeno.json: checks thatdeno.lockcovers everyjsr:andnpm:import, including workspace members. Deno updates the lock on the next run, butdeno install --frozen(CI) fails until it's committed, so a stale lock is a warning withdeno installas the fix.deno.jsonfiles: an invalid one (root or workspace member) is reported with the parse error.- Workspaces: missing
"workspace"members (which Deno silently skips) are flagged, and glob members (./packages/*) are supported. - Deno itself: if the project uses Deno but it isn't installed, doctor says so.
--from-errorfor Deno's own errors:Import "x" not a dependency: suggests thedeno addcommand.- JSR or npm version not found, and JSR package not found.
- Checksum mismatches against
deno.lock: re-download with--reloadfirst, then fix the lockfile. Unsupported lockfile version: suggestsdeno upgrade.- Invalid
deno.jsonand missing workspace members. - Runtime permission errors (
Requires read access ⦠--allow-read): suggests the narrowest grant, e.g.--allow-read=deno.json.
- Cleanup:
--lockfilesalso removesdeno.lock;--installrunsdeno install. --from-error: recognises Deno's frozen-lockfile error, its legacy-addon error and its minimum-dependency-age error.- Git hook: reacts to changes in
deno.lockanddeno.json. - Agent guard: blocks deleting
deno.lock. On machines with Deno but no Node, the hook runs the guard with Deno.
Installation
Global Installation
npm install -g cleaninstall-node
Local Installation
npm install --save-dev cleaninstall-node
Usage
Command Line
After installing globally, you can run:
cleaninstall-node [options]
Or if installed locally:
npx cleaninstall-node [options]
Options
Usage: cleaninstall-node [options]
A utility to clean up Node.js project files
Options:
-V, --version output the version number
-d, --dir <directory> root directory to clean (defaults to current directory)
-v, --verbose print verbose output (default: true)
--no-verbose disable verbose output
--depth <number> how deep to scan for packages when no workspaces are defined
--skip-git skip .git directories (default)
--no-skip-git do not skip .git directories
--dry-run show what would be deleted without deleting (default: false)
-i, --interactive prompt before deleting each item (default: false)
-y, --yes don't ask for confirmation before deleting
--lockfiles also remove lockfiles (package-lock.json, yarn.lock, pnpm-lock.yaml, bun.lock)
--install run the package manager's install after cleanup (default: false)
-h, --help display help for command
When run in a terminal, the tool lists everything it will remove with sizes and asks once before deleting. The prompt is skipped with -y, in --dry-run / -i mode, and when stdin isn't a terminal (CI, pipes).
Common Use Cases
# Clean a monorepo and reinstall all dependencies
npx cleaninstall-node --install
# Preview what would be removed
npx cleaninstall-node --dry-run
# Clean before committing to save disk space
npx cleaninstall-node
# Add to package.json scripts for convenience
{
"scripts": {
"clean": "cleaninstall-node -y",
"fresh": "cleaninstall-node -y --install",
"clean:preview": "cleaninstall-node --dry-run"
}
}
Programmatic Usage
const { cleanup } = require("cleaninstall-node");
const result = await cleanup({
dir: "/path/to/project",
dryRun: true, // report only
removeLockfiles: false, // keep lockfiles (default)
dirsToRemove: ["node_modules", "dist"],
verbose: false,
});
console.log(result.removed); // absolute paths removed (or that would be, in dry run)
console.log(result.totalSize); // bytes freed
console.log(result.packageManager); // "npm" | "yarn" | "pnpm" | "bun"
cleanup() does not show the up-front confirmation prompt (it acts as if yes: true). It resolves to { dryRun, packageManager, targets, removed, skipped, failed, totalSize, totalFiles, itemsDeleted, installed }.
Key Features Explained
Workspace Detection
The tool automatically looks for workspaces definitions in your root package.json and packages definitions in pnpm-workspace.yaml. If found, it uses these patterns (via glob) to identify workspace directories and cleans them alongside the root directory. The --depth option is mainly used as a fallback if no workspace definitions are found, controlling how deep to look for nested package.json files.
Glob Patterns
You can use glob patterns in the dirsToRemove and filesToRemove configuration arrays. For example:
"*.log": Removes all files ending in.log."temp-*": Removes all files or directories starting withtemp-.".cache": Removes a directory named.cache. (Dot files/dirs are included by default).
Dry Run (--dry-run)
Simulates the cleanup process. It prints all files and directories that would be deleted according to the configuration and workspace detection, but doesn't actually modify the file system. Useful for verifying your setup.
Interactive (-i, --interactive)
Prompts for confirmation (Y/N) before deleting each identified file or directory. This gives you fine-grained control over the cleanup process.
Auto-Install (--install)
After a successful cleanup (and if not in dry-run mode), this runs your package manager's install in the root directory. The package manager is detected before anything is deleted: first from the packageManager field in package.json (Corepack), then from pnpm-lock.yaml, yarn.lock, bun.lock/bun.lockb or package-lock.json, defaulting to npm. Set installCommand in config (e.g. "npm ci") to run something else.
Lockfiles (--lockfiles)
Lockfiles are kept by default: deleting them makes the next install resolve new dependency versions, which is rarely what a "clean reinstall" should do. Pass --lockfiles (or removeLockfiles: true in config/API) to remove package-lock.json, npm-shrinkwrap.json, yarn.lock, pnpm-lock.yaml, bun.lock and bun.lockb.
Configuration
Configure using command-line options (highest precedence), a .cleaninstallnoderc file (JSON format) in the project root, or a cleaninstallNode key in your root package.json.
Example package.json Configuration
{
"name": "your-project",
"version": "1.0.0",
"cleaninstallNode": {
"dirsToRemove": [
"node_modules",
".next",
"dist",
"build",
"coverage",
"*.tmp"
],
"filesToRemove": [
"package-lock.json",
"yarn.lock",
"pnpm-lock.yaml",
"*.log"
],
"skipDirs": [".git", "docs", ".vscode"]
}
}
Example .cleaninstallnoderc File
{
"dirsToRemove": ["node_modules", "dist", "build", ".cache"],
"filesToRemove": ["*-lock.json", "yarn.lock", "pnpm-lock.yaml"],
"skipDirs": [".git", "artifacts"]
}
Configuration Options
| Option | Type | Default | Description |
|---|---|---|---|
dirsToRemove | string[] | ["node_modules", ".next", ".turbo", "dist", "build", ".cache", ".nuxt", ".output", "out", ".vite", ".astro", ".svelte-kit", "coverage", ".nyc_output"] | Directories to remove (supports glob patterns). Matched relative to each directory being cleaned. |
filesToRemove | string[] | [] | Files to remove (supports glob patterns). Matched relative to each directory being cleaned. |
removeLockfiles | boolean | false | Also remove all known lockfiles (same as --lockfiles). |
installCommand | string | string[] | detected | Command run by --install, e.g. "npm ci". |
scanDepth | number | 2 | Fallback scan depth if no workspaces detected (1 = root only, 2 = root + immediate children with package.json) |
skipDirs | string[] | [".git"] | Base names of directories to completely ignore during scanning and glob matching. |
verbose | boolean | true | Whether to print verbose output. |
(Note: workspacePatterns are automatically detected and not typically set manually in config)
Development
Testing
This project uses Jest for testing. To run the tests:
npm test
The tests should ideally use mocking libraries (like mock-fs, or Jest's mocking capabilities for fs, glob, execa, readline) to simulate file system operations and external processes without side effects.
Publishing
To publish this package to npm:
-
Make sure you have an npm account and are logged in:
npm login -
Update the version in package.json:
npm version patch # or minor, or major -
Publish the package:
npm publish
License
MIT
cleaninstall-nodenpm install cleaninstall-node