使用命令行从指定路径递归删除 node_modules 文件夹

Delete node_modules folder recursively from a specified path using command line

我在本地目录中保存了多个 npm 项目。现在我想在没有 node_modules 文件夹的情况下备份我的项目,因为它占用了很多 space 并且也可以随时使用 npm install.

进行检索

因此,我需要一个解决方案来使用命令行界面从指定路径递归删除所有 node_modules 文件夹。 非常感谢任何建议/帮助。

我遇到过这个解决方案,

  • 首先使用find找到文件夹并指定文件夹名称。
  • 递归执行删除命令-exec rm -rf '{}' +

运行以下命令递归删除文件夹

find /path -type d -name "node_modules" -exec rm -rf '{}' +

打印出要删除的目录列表:

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

从当前工作目录中删除目录:

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

或者您可以使用 trash (brew install trash) 进行分阶段删除:

find . -name node_modules -type d -prune -exec trash {} +

改进已接受的答案,

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

我发现该命令会 运行 很长时间来获取所有文件夹,然后 运行 删除命令,使命令可恢复我建议使用 \;并查看命令的进度 运行 使用 -print 查看正在删除的目录。

注意:您必须先cd进入根目录,然后运行执行命令或使用[=18]代替find . =]

逐一删除文件夹

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

逐一删除文件夹并打印正在删除的文件夹

find . -name 'node_modules' -type d -prune -print -exec rm -rf '{}' \;

编辑:

对于喜欢交互式方式的人,请参考@jeckep 的回答,运行 这在您希望 p运行e 的目录中。

npx npkill

试试看 https://github.com/voidcosmos/npkill

npx npkill

它将找到所有 node_modules 并让您删除它们。

bash 函数删除 node_modules。它将递归地从当前工作目录中删除所有 node_modules 目录, 在打印找到的路径时。

您只需要在 $PATH

中的某处输入
rmnodemodules(){

  find . -name 'node_modules' -type d -prune -exec echo '{}' \; -exec rm -rf {} \; 

}

在 Windows 时,我使用以下 .BAT 文件从当前文件夹递归删除 node_modules

@for /d /r . %d in (node_modules) do @if exist %d (echo %d && rd %d /s /q) 

或者,通过 CMD.EXE:

cmd.exe /c "@for /d /r . %d in (node_modules) do @if exist %d (echo %d && rd %d /s /q)"

Python 从多个项目中删除 node_modules 文件夹的脚本。只需将它放在包含多个项目的项目文件夹中,然后 运行 它。

import os
import shutil
dirname = '/root/Desktop/proj' #Your Full Path of Projects Folder
dirfiles = os.listdir(dirname)

fullpaths = map(lambda name: os.path.join(dirname, name), dirfiles)

dirs = []

for file in fullpaths:
    if os.path.isdir(file): dirs.append(file)

for i in dirs:
    dirfiles1 = os.listdir(i)
    fullpaths1 = map(lambda name: os.path.join(i, name), dirfiles1)
    dirs1 = []
    for file in fullpaths1:
        if os.path.isdir(file):
            dirs1.append(file)
            if(file[-12:]=='node_modules'):
                shutil.rmtree(file)
                print(file)
    

OS: Ubuntu

删除服务器中所有 node_modules 的一个简单技巧(可以减少很多 space)是 运行:

sudo find / -not -path "/usr/lib/*" -name 'node_modules' -type d -prune -exec rm -rf '{}' + 

这里我们需要排除 /usr/lib/* 因为如果你不这样做,它会删除你的 npm 并且你需要重新安装它:)

如果您想移动而不是删除它:

find . -name 'node_modules' -type d -prune -exec mkdir -p ./another/dir/{} \; -exec mv -i {} ./NODE_MODULES/{} \;

这将保持目录结构。