如何删除机器上的所有 node_modules 文件夹并释放高清空间!

2025-05-28

如何删除机器上的所有 node_modules 文件夹并释放高清空间!

最初于 2019 年 8 月 7 日发表在Trilon 博客上。

每当我们开展新项目时,我们都需要运行npm install,但我们多久会考虑一下这会对我们的硬盘造成什么损害?

可怕的“空间不足”信息

单个 node_modules 文件夹可能占用 200+ MB 的空间(有时甚至 1GB+!)。

现在查看一下您的github/文件夹,或者存储大部分项目的任何其他地方,您就可以开始看到部分可用硬盘空间去了哪里!

我最近在推特上发布了这个消息,因为这是我每隔几个月就会使用一次的东西,并且想与可能遇到过同样情况的其他人分享!

列出目录中找到的所有 node_modules:

首先,在实际开始删除它们之前,让我们先看看目录中的所有node_modules!

注意:确保您进入大多数项目所在的特定目录。即:documentsdocuments/github

Mac / Linux:

此命令将打印出每个文件夹,甚至显示每个文件夹占用的空间大小!感谢Rhymes提供的提示!

$ cd documents
$ find . -name "node_modules" -type d -prune -print | xargs du -chs

--- Example output ---
1.0G ./Github/big-project/node_modules
225M ./Github/Trilon.io/node_modules
482M ./Github/Some_Demo/node_modules

1.7G total
Enter fullscreen mode Exit fullscreen mode

视窗:

$ cd documents
$ FOR /d /r . %d in (node_modules) DO @IF EXIST "%d" echo %d"
Enter fullscreen mode Exit fullscreen mode

此列表将让您清楚地了解您的机器上安装的项目数量!


删除目录中找到的所有 node_modules:

注意:这里要小心,并确保您位于可以轻松删除所有node_modules 实例的目录中,在删除之前运行上面的脚本以查看它们的完整列表。

这个脚本实际上与上面的脚本非常相似,但我们将使用它rm -rf来彻底删除它们。

警告:此过程不可逆!

Mac / Linux:

$ cd documents
$ find . -name 'node_modules' -type d -prune -print -exec rm -rf '{}' \;
Enter fullscreen mode Exit fullscreen mode

视窗:

$ cd documents
$ FOR /d /r . %d in (node_modules) DO @IF EXIST "%d" rm -rf "%d"
Enter fullscreen mode Exit fullscreen mode

Powershell 用户:

Get-ChildItem -Path "." -Include "node_modules" -Recurse -Directory | Remove-Item -Recurse -Force
Enter fullscreen mode Exit fullscreen mode

就是这样!

就我个人而言,这通常会从我的硬盘中清除大约 40-60GB 的空间,但您的情况可能会有所不同!

综上所述

  • 在删除之前,请确保列出给定目录中的所有 node_modules 。
  • 请务必小心,因为这个过程是不可逆的
  • 记住要npm install再次进行您需要开展的项目。
  • 享受自由空间!:)

在下面发表评论,我很想知道您节省了多少钱!

另外,别忘了查看Trilon 博客以获取更多深入的文章!

文章来源:https://dev.to/trilon/how-to-delete-all-nodemodules-folders-on-your-machine-43dh
PREV
How to Pass a Programming Interview
NEXT
🚀 使用 NextJS、Replicate 和 Trigger.dev 将您的脸变成超级英雄🦸🏻‍♂️ TL;DR