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

# 全局缓存

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

所有从注册表下载的包都存储在全局缓存中，路径为 `~/.bun/install/cache`，或者环境变量 `BUN_INSTALL_CACHE_DIR` 定义的路径。它们存储在名为 `${name}@${version}` 的子目录中，因此可以缓存同一个包的多个版本。

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

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

  # 为 true 时，总是从注册表解析最新版本
  disableManifest = false
  ```
</Accordion>

***

## 减少重复下载

Bun 力求避免多次重复下载包。安装包时，如果缓存中已有符合 `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`。否则，将从注册表下载该包并安装。
</Accordion>

***

## 快速复制

包一旦下载到缓存中，Bun 还需将这些文件复制到 `node_modules`。Bun 使用最快的系统调用来完成此操作。在 Linux 上使用硬链接；在 macOS 上使用 `clonefile`。

***

## 节省磁盘空间

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

该优势同样适用于 macOS，但存在例外。macOS 使用的是基于写时复制（copy-on-write）的 `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` 目录，或你传递 `--preserve-symlinks` 参数给 `node`，否则不会解析依赖的 `node_modules`。详见 [Node.js 文档中关于 `--preserve-symlinks`](https://nodejs.org/api/cli.html#--preserve-symlinks)。

  ```bash terminal icon="terminal" theme={"theme":{"light":"github-light","dark":"dracula"}}
  bun install --backend symlink
  node --preserve-symlinks ./foo.js
  ```

  Bun 的运行时目前不支持等价于 `--preserve-symlinks` 的选项。
</Accordion>
