> ## Documentation Index
> Fetch the complete documentation index at: https://bun.ll1025.cn/llms.txt
> Use this file to discover all available pages before exploring further.

# 全局缓存

> Bun 如何在其全局缓存中存储和管理包

Bun 将从注册表下载的每个包存储在全局缓存中，位置在 `~/.bun/install/cache`，或由 `BUN_INSTALL_CACHE_DIR` 环境变量指定的路径。包以 `${name}@${version}` 格式的子目录名称存储，因此可以缓存一个包的多个版本。

<Accordion title="配置缓存行为">
  ```toml bunfig.toml icon="settings" theme={null}
  [install.cache]
  # 缓存使用的目录
  dir = "~/.bun/install/cache"

  # 如果为 true，不从全局缓存加载。
  # Bun 可能仍会写入 node_modules/.cache
  disable = false

  # 如果为 true，始终从注册表解析最新版本
  disableManifest = false
  ```
</Accordion>

***

## 减少重复下载

安装包时，如果缓存中已包含 `package.json` 指定范围内的版本，Bun 会使用缓存副本，而不重新下载。

<Accordion title="安装详情">
  如果 semver 版本有预发布后缀（`1.0.0-beta.0`）或构建后缀（`1.0.0+20220101`），则该值会被替换为该值的哈希，以减少长文件路径导致的错误。

  当 `node_modules` 文件夹存在时，在安装之前，Bun 会检查 `node_modules` 是否包含所有预期包且版本正确。如果是，`bun install` 完成。Bun 使用自定义 JSON 解析器，一旦找到 `"name"` 和 `"version"` 就停止解析。

  如果包缺失或版本与 `package.json` 不兼容，Bun 会在缓存中查找兼容的模块。如果找到，则安装到 `node_modules` 中。否则，Bun 从注册表下载包，然后安装。
</Accordion>

***

## 快速复制

包下载到缓存后，Bun 仍然需要将这些文件复制到 `node_modules` 中。它使用可用的最快系统调用：Linux 上的硬链接（hardlink），macOS 上的 `clonefile`。

***

## 节省磁盘空间

由于 Bun 使用硬链接在 Linux 和 Windows 上将模块"复制"到项目的 `node_modules` 目录，因此包的内容只存在于磁盘上的一个位置，大大减少了 `node_modules` 占用的磁盘空间。

macOS 上也适用同样的原理，但有一个注意事项。Bun 在 macOS 上使用 `clonefile`，这是写时复制：克隆不占用额外磁盘空间，但会计入驱动器的限制。由于复制只在写入时发生，在一个项目中修补 `node_modules/*` 不会影响其他安装。

<Accordion title="安装策略">
  使用 `--backend` 标志配置此项，Bun 的所有包管理命令都支持该标志。

  * **`hardlink`**：Linux 和 Windows 上的默认值。
  * **`clonefile`**：macOS 上的默认值。
  * **`clonefile_each_dir`**：与 `clonefile` 类似，但每个目录单独克隆每个文件。仅在 macOS 上可用，通常比 `clonefile` 慢。
  * **`copyfile`**：上述方法失败时使用的回退方案。是最慢的选项。在 macOS 上使用 `fcopyfile()`；在 Linux 上使用 `copy_file_range()`。
  * **`symlink`**：仅用于 `file:`（以及将来的 `link:`）依赖。为防止无限循环，会跳过符号链接 `node_modules` 文件夹。

  如果使用 `--backend=symlink` 安装，Node.js 将无法解析依赖的 node\_modules，除非每个依赖都有自己的 `node_modules` 文件夹，或者你向 `node` 传递 `--preserve-symlinks`。请参阅 [Node.js 关于 `--preserve-symlinks` 的文档](https://nodejs.org/api/cli.html#--preserve-symlinks)。

  ```bash terminal icon="terminal" theme={null}
  bun install --backend symlink
  node --preserve-symlinks ./foo.js
  ```

  Bun 的运行时也支持 `--preserve-symlinks`。
</Accordion>
