Monday, August 5, 2019

Delete node_modules folder recursively from a specified path using command line.

Answers from StackOverflow. Click here for the whole discussion thread.
Print out a list of directories to be deleted:
find . -name 'node_modules' -type d -prune
Delete directories from the current working directory:
find . -name 'node_modules' -type d -prune -exec rm -rf '{}' +

Alternatively, you can use trash (brew install trash) for staged deletion:
find . -name node_modules -type d -prune -exec trash {} +


Another answer from StackOverflow,
find . -name 'node_modules' -type d -prune -exec rm -rf '{}' +
I found that the command would run a very long time to fetch all folders and then run a delete command, to make the command resumable I'd suggest using \; and to see progress of the command being run use -print to see the directory being deleted.
Note: You must first cd into the root directory and then run the command or instead of find . use find {project_directory}
To delete folders one by one
find . -name 'node_modules' -type d -prune -exec rm -rf '{}' \;
To delete folders one by one and printing the folder being deleted
find . -name 'node_modules' -type d -prune -print -exec rm -rf '{}' \;