DEV Community

Sh Raj
Sh Raj

Posted on

How to Delete All `node_modules` Folders in Your System Using Python

How to Delete All node_modules Folders in Your System Using Python

Managing your node_modules folders can quickly become a nightmare for developers, especially if you're working on multiple projects. These folders tend to consume gigabytes of disk space and clutter your file system. This article will guide you through using a Python script to find and delete all node_modules folders in your system safely and efficiently.


Why Clean Up node_modules?

The node_modules folder is crucial for running JavaScript projects, as it stores all the dependencies required by the project. However, it has some downsides:

  • Disk Space: Each node_modules folder can consume hundreds of megabytes or even gigabytes of storage. Over time, these add up.
  • System Performance: Large folders can slow down system scans, backups, and file searches.
  • Clutter: Keeping old or unused node_modules folders can make your development environment messy.

By cleaning up unused node_modules folders, you free up space, improve system performance, and create a cleaner development environment.


The Solution: A Python Script

This Python script scans your system for all node_modules folders and gives you options to:

  1. Preview the folders before deletion.
  2. Delete them permanently or move them to the recycle bin.

The Script

Hereโ€™s the Python script:

import os
import shutil
from send2trash import send2trash

def find_node_modules(start_path):
    """
    Finds all 'node_modules' folders starting from the given path.

    :param start_path: Directory path to begin the search.
    :return: List of paths to 'node_modules' folders.
    """
    node_modules_paths = []
    for root, dirs, files in os.walk(start_path):
        if 'node_modules' in dirs:
            node_modules_paths.append(os.path.join(root, 'node_modules'))
    return node_modules_paths

def delete_folders(folders, permanently=True):
    """
    Deletes the specified folders either permanently or moves them to the recycle bin.

    :param folders: List of folder paths to delete.
    :param permanently: If True, deletes permanently. If False, moves to recycle bin.
    """
    for folder in folders:
        try:
            if permanently:
                shutil.rmtree(folder)
                print(f"Deleted permanently: {folder}")
            else:
                send2trash(folder)
                print(f"Moved to recycle bin: {folder}")
        except Exception as e:
            print(f"Error deleting {folder}: {e}")

if __name__ == "__main__":
    # Get the starting directory from the user
    start_directory = input("Enter the directory to start searching for 'node_modules' (e.g., C:\\ or /): ").strip()
    if os.path.exists(start_directory):
        print("Scanning for 'node_modules' folders. This may take some time...")
        node_modules_paths = find_node_modules(start_directory)

        if node_modules_paths:
            print(f"\nFound {len(node_modules_paths)} 'node_modules' folders:")
            for idx, path in enumerate(node_modules_paths, start=1):
                print(f"{idx}. {path}")

            # Confirm before proceeding
            confirm = input("\nDo you want to delete these folders? (yes/no): ").strip().lower()
            if confirm == 'yes':
                # Choose delete mode
                mode = input("Delete permanently or move to recycle bin? (permanent/recycle): ").strip().lower()
                permanently = mode == 'permanent'

                print("\nDeleting folders...")
                delete_folders(node_modules_paths, permanently)
                print("\nProcess complete!")
            else:
                print("No folders were deleted.")
        else:
            print("No 'node_modules' folders found.")
    else:
        print("The provided directory does not exist!")
Enter fullscreen mode Exit fullscreen mode

How to Use the Script

  1. Install Python: Make sure Python is installed on your system.
  2. Install Dependencies: Install the send2trash library for safely moving files to the recycle bin.
   pip install send2trash
Enter fullscreen mode Exit fullscreen mode
  1. Run the Script: Save the script as delete_node_modules.py and run it:
   python delete_node_modules.py
Enter fullscreen mode Exit fullscreen mode
  1. Follow the Prompts:
    • Enter the root directory to scan (e.g., C:\ on Windows or / on Linux/Mac).
    • Review the list of node_modules folders found.
    • Choose whether to delete them permanently or move them to the recycle bin.

Benefits of Cleaning node_modules

  1. Reclaim Disk Space: Free up gigabytes of storage by removing unused node_modules folders.
  2. Improve System Performance: Faster backups, scans, and searches.
  3. Declutter Your Projects: Keep your development environment neat and manageable.
  4. Peace of Mind: With the recycle bin option, you can restore mistakenly deleted folders.


Best Practices for Managing node_modules

To prevent excessive buildup of node_modules in the future:

  1. Regularly delete old or unused projects.
  2. Use global installations for commonly used tools like eslint or typescript.
  3. Consider using pnpm for dependency management, which uses a shared store for dependencies instead of duplicating them in each project.

Conclusion

Cleaning up your node_modules folders is a small but impactful step in optimizing your development workflow. This Python script makes it easy, efficient, and safe. So give it a try, and let me know how much space you managed to free up!


Let me know your thoughts in the comments below! If you found this article helpful, feel free to share it and follow me for more developer tips and tricks.

Top comments (0)