I have seen a number of developers facing issues with disk space being consumed heavily by 'node_modules' folders, especially when working with JavaScript projects. To assist with this, I have developed a Python script that quickly and efficiently deletes all 'node_modules' folders in a directory and its immediate subdirectories.
The script uses multi-threading to enhance the speed of the deletion process.
import os
import shutil
from concurrent.futures import ThreadPoolExecutor
def delete_node_modules_path(node_modules_path):
try:
shutil.rmtree(node_modules_path)
print(f"Successfully deleted the folder: {node_modules_path}")
except Exception as e:
print(f"Could not delete the folder {node_modules_path} due to the following error: {e}")
def delete_node_modules(base_path):
# Verify if the provided path exists
if not os.path.exists(base_path):
print(f"The specified path does not exist: {base_path}")
return
# Get a list of all immediate subdirectories
subdirs = [os.path.join(base_path, d) for d in os.listdir(base_path) if os.path.isdir(os.path.join(base_path, d))]
# Traverse only one level down the directory structure and delete 'node_modules' folders
with ThreadPoolExecutor() as executor:
for subdir in subdirs:
node_modules_path = os.path.join(subdir, 'node_modules')
if os.path.exists(node_modules_path):
print(f"Processing: {subdir}")
executor.submit(delete_node_modules_path, node_modules_path)
if __name__ == "__main__":
base_path = os.getcwd()
print(f"The current base path is: {base_path}")
delete_node_modules(base_path)