Cleaning up deep, nested directories like node_modules is a perfect use case for modern CLI tools. While rg (ripgrep) is the king of searching inside files, fd is the absolute best tool for finding and acting upon files and directories.
Here is the fastest, most efficient fd one-liner to securely wipe node_modules (or any other target) in your current directory and all subdirectories.
To immediately find and delete every node_modules folder, run this in your Fish shell:
Code snippet
fd -IH '^node_modules$' -x rm -rf-
fd: Invokes thefd-findtool. -
-I(--no-ignore): Crucial. By default,fdrespects your.gitignorefiles. Sincenode_modulesis almost always git-ignored, you must use-Isofdactually sees them. -
-H(--hidden): Ensures it searches inside hidden directories just in case. -
^node_modules$: The search pattern.fduses regex by default. The^(start) and$(end) ensure you only delete folders named exactly "node_modules" and don't accidentally nuke a folder namedmy_node_modules_backup. -
-x rm -rf: The execution flag. For every matchfdfinds, it immediately executesrm -rfagainst it.
To delete a different file or directory: Simply replace
node_modulesin the quotes (e.g.,fd -IH '^\.DS_Store$' -x rm -rf). Becauserm -rfforces deletion on both files and folders, this command works universally.
If you do this often, you can create a dedicated Fish function. It includes a safety check to count the matches before it deletes anything.
Run funced nuke in your terminal, paste the following, and then run funcsave nuke:
Code snippet
function nuke -d "Recursively delete a specific file or folder"
# Take the first argument, default to node_modules if empty
set target $argv[1]
if test -z "$target"
set target "node_modules"
end
echo "Scanning for exact matches of '$target' in "(pwd)"..."
# Do a dry run to count matches
set match_count (fd -IH "^$target\$" | wc -l)
if test $match_count -eq 0
echo "Nothing to delete! ✨"
return 0
end
echo "Found $match_count match(es). Nuking..."
# Execute the deletion
fd -IH "^$target\$" -x rm -rf
echo "Cleanup complete! 🧹"
endHow to use the function:
-
nuke➔ Deletes allnode_modulesanywhere in the current tree. -
nuke coverage➔ Deletes all folders/files named exactlycoverage. -
nuke .eslintcache➔ Deletes all your ESLint cache files.
While fd is the fastest raw CLI method, if you specifically want to free up hard drive space by deleting old node_modules across your entire machine, you can run npx npkill. It provides an interactive, keyboard-driven UI right in your terminal, sorting all your node_modules folders by size and letting you delete them one by one with the Spacebar.