Recursively delete node_modules

node_modules directories can take up a lot of space in your development environment. Here's how to find and delete them efficiently.


Understanding the Commands

  1. Locate node_modules directories:

    find . -name 'node_modules' -type d -prune
    

    This command starts searching from your current directory (.) for anything named node_modules. The -type d flag ensures it only looks for directories, and -prune is key: it tells find to not look inside any node_modules directory it finds, which speeds things up significantly.

  2. Recursively delete node_modules directories:

    find . -name 'node_modules' -type d -prune -exec rm -rf '{}' +
    

    This command extends the previous one. Once a node_modules directory is found, -exec rm -rf '{}' + runs the rm -rf command on it.

    • rm -rf: This forcefully (-f) removes directories and their contents recursively (-r).

    • '{}' +: This efficiently passes all found node_modules directories to rm -rf in one go, rather than running a separate rm command for each one.


How to Use

  1. Navigate: Go to the main directory where you want to start the cleanup (e.g., your projects folder).

    cd /path/to/your/projects
    
  2. Preview (Highly Recommended): Always run the first command alone to see which node_modules folders will be affected before deleting. Bash

    find . -name 'node_modules' -type d -prune
    

    Check the output to make sure it looks correct.

  3. Delete: Once you're sure, run the full command to remove them. Bash

    find . -name 'node_modules' -type d -prune -exec rm -rf '{}' +
    

Important Notes

  • Be Careful: rm -rf deletes files permanently, with no undo. Double-check your current directory before running the delete command.

  • Backup: If you're working on critical projects, it's always a good idea to back up your code first.

Updated on