Remove node_modules from all folders
Remove all node_modules recursive from every folder
If you want to remove all node_modules from all project files.
How much space node_modules are using in your disk in Mac
$ cd projects
$ find . -name "node_modules" -type d -prune | xargs du -chs
/* Sample Output */
28M ./image-resize/node_modules
14M ./backend/node_modules
217M ./hectane-next/node_modules
259M total
With the above code you can see how much node_modules are using your disk space.
NodeJs way
const fs = require('fs');
const removeNodeModules = (base) => {
fs.readdirSync(base).forEach((path) => {
if (fs.statSync(`${base}/${path}`).isDirectory()) {
if (path !== 'node_modules') {
removeNodeModules(`${base}/${path}`);
} else {
fs.rmdir(`${base}/${path}`, { recursive: true }, (err) => {
if (err) {
throw err;
}
console.log(`${base}/${path} is deleted!`);
});
}
}
});
};
removeNodeModules('./');
Save the above code as remove_node_modules.js and then run in the parent folder.
node remove_node_modules.js
It will remove all node_modules folders from all sub directories.
// Required node.js to be configured
Note: If you need some granular control then you can use the NodeJs. Here we can even ignore some folders by skipping that folder names in the if check.
Mac way
This code I have been using earlier in mac.
$ cd projects
$ find . -name "node_modules" -type d -prune -exec rm -rf '{}' +
Windows way
cd projects
FOR /d /r . %d in (node_modules) DO @IF EXIST "%d" rm -rf "%d"