Repository avatar
Developer Tools
v3.4.1
active

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

npm version Downloads License: MIT CI cleaninstall-node MCP server

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.

Website Ā· npm Ā· Changelog

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 -y in 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.json or pnpm-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 install adds guidance to AGENTS.md / CLAUDE.md and a Claude Code hook that blocks rm -rf node_modules and 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, pnpm or bun install after cleanup, detected from the packageManager field 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
CheckDetectsFix
Node versionRunning Node vs .nvmrc, .node-version, .tool-versions, volta.node, engines.nodeManual (nvm use). Blocks --fix so nothing is rebuilt for the wrong Node
Lockfile syncnode_modules doesn't match the lockfile, e.g. after a git pull (npm, pnpm, yarn v1)install
Direct dependenciesA dependency is missing or installed outside its package.json range (all package managers, workspaces included)install
Native modulesA .node addon was built for another Node ABI, or for another OS/CPU (Docker volume, Rosetta)rebuild <only those packages>
Installernode_modules was written by a different package manager than the project usesremove node_modules + install
LockfilesMore than one package manager's lockfile, a mismatch with packageManager, no lockfile at allManual
pnpm buildspnpm 10 skipped a package's build scripts (ignoredBuilds)Manual (pnpm approve-builds)
yarn systemyarn v1 installed under a different Node ABI or platforminstall

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:

ErrorExampleWhat it suggests
Native module, wrong NodeNODE_MODULE_VERSION 115 … requires 127Rebuild that one package
Native module, wrong OS/CPUinvalid ELF headerRebuild that package, and stop sharing node_modules with Docker
Platform binary missingrollup, esbuild, sharp, swc …-linux-x64Clean reinstall
Module not foundNode CJS/ESM, Vite, webpack, Next.js, TS2307Depends on the project (see above)
Command not foundsh: vite: not found, 'tsc' is not recognizedInstall, npx, or which package to add
ESM-only packageERR_REQUIRE_ESMNewer Node, import(), or pin the old major
Subpath not exportedERR_PACKAGE_PATH_NOT_EXPORTEDCheck the installed major
Lockfile out of syncnpm ci, ERR_PNPM_OUTDATED_LOCKFILE, yarn --frozen-lockfileInstall locally and commit the lockfile
Peer conflictERESOLVEAlign versions (--legacy-peer-deps only as a last resort)
Wrong Node for a dependencyEBADENGINE, yarn/pnpm engine errorsSwitch Node (blocks --fix)
Wrong package managerCorepack mismatch, npm on workspace:Use the declared package manager
Broken installENOTEMPTY, interrupted installsClean reinstall
OtherEINTEGRITY, 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.

ToolWhat it doesChanges files
explain_errorExplains an error message for this project (everything --from-error knows) and returns a fix planNo
diagnoseFull doctor health check and fix planNo
apply_fixRuns the plan: targeted rebuild, install, or (rarely) a clean reinstall. Never touches lockfilesYes
plan_cleanLists what a cleanup would delete, with sizesNo
cleanDeletes exactly what plan_clean listed; can reinstallYes

Built-in safety:

  • Plans must be shown first. apply_fix and clean only run with the plan_id from 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 a package.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_error before deleting node_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
FileWhat it gets
AGENTS.mdA short "diagnose before deleting" section, read by most coding agents
CLAUDE.mdThe 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.jsA 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 with npx cleaninstall-node agent check <command>.
  • Settings are merged: your permissions and other hooks are kept, and an invalid settings.json is 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_modules and the agent relayed the reason. Behaviour in bypassPermissions mode 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) and post-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, .npmrc or .yarnrc.yml changed, it exits immediately. When one did, it runs doctor's checks and stays silent if node_modules already matches.
  • Safe: --mode install only ever runs an install or a targeted rebuild. It never deletes node_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 CI is set. Skip once with CLEANINSTALL_SKIP_HOOK=1 git pull; override the mode per shell with CLEANINSTALL_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
CommandPermissions
doctor, doctor --from-error, cleanup --dry-run--allow-read --allow-env
doctor checking native modulesadd --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_modules against deno.lock, e.g. after a git pull (Deno stores packages in node_modules/.deno). Optional binaries for other platforms are skipped.
  • deno.json imports: 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/.deno is removed, then deno install --allow-scripts=… runs.
  • Global cache: deno.json-only projects without nodeModulesDir keep 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.lock vs deno.json: checks that deno.lock covers every jsr: and npm: import, including workspace members. Deno updates the lock on the next run, but deno install --frozen (CI) fails until it's committed, so a stale lock is a warning with deno install as the fix.
    • deno.json files: 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-error for Deno's own errors:
    • Import "x" not a dependency: suggests the deno add command.
    • JSR or npm version not found, and JSR package not found.
    • Checksum mismatches against deno.lock: re-download with --reload first, then fix the lockfile.
    • Unsupported lockfile version: suggests deno upgrade.
    • Invalid deno.json and missing workspace members.
    • Runtime permission errors (Requires read access … --allow-read): suggests the narrowest grant, e.g. --allow-read=deno.json.
  • Cleanup: --lockfiles also removes deno.lock; --install runs deno 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.lock and deno.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 with temp-.
  • ".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

OptionTypeDefaultDescription
dirsToRemovestring[]["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.
filesToRemovestring[][]Files to remove (supports glob patterns). Matched relative to each directory being cleaned.
removeLockfilesbooleanfalseAlso remove all known lockfiles (same as --lockfiles).
installCommandstring | string[]detectedCommand run by --install, e.g. "npm ci".
scanDepthnumber2Fallback scan depth if no workspaces detected (1 = root only, 2 = root + immediate children with package.json)
skipDirsstring[][".git"]Base names of directories to completely ignore during scanning and glob matching.
verbosebooleantrueWhether 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:

  1. Make sure you have an npm account and are logged in:

    npm login
    
  2. Update the version in package.json:

    npm version patch  # or minor, or major
    
  3. Publish the package:

    npm publish
    

License

MIT

NPM
cleaninstall-node
Install Command
npm install cleaninstall-node
Runtime: npx