# npm 缓存

## npm install 中的缓存

`npm@5.x` 版本中，`npm install` 会将模块下载到 `node_modules` 目录，并生成 `package-lock.json` 文件。

### 缓存目录

`npm install` 或 `npm update` 命令，从远程仓库下载压缩包之后，会将压缩包和相关信息保存到本地的缓存目录。在 Linux 或 Mac 中，缓存目录是 `~/.npm`，在 Windows 中，缓存目录是 `%LocalAppData%\npm-cache`。

```bash
# 查看缓存目录
npm config get cache
```

缓存的包就放在 `.npm/_cacache` 目录下，

!\[image-20241008160153518]\(/Users/liangzhiwei/Library/Application Support/typora-user-images/image-20241008160153518.png)

* `content-v2` 目录：保存着二进制文件
* `index-v5` 目录：保存着二进制文件的索引

`npm` 在执行安装时，可以根据 `package-lock.json` 文件中记录的依赖包信息(`integrity`、`version`、`name`)生成唯一的 `key` ，对应到 `index-v5` 目录中找对应的文件， 然后从缓存目录中找到对应的压缩包，然后解压复制到 `node_modules` 目录中。

![npm install 缓存](https://i-blog.csdnimg.cn/blog_migrate/1d48f9fb0100304adb71ef41db936cc8.png)

### 缓存机制

1. `npm install` 在执行的时候，首先构建依赖树，一次安装依赖树中的每个包。
2. 在安装某个包的时候，会先从缓存中查找是否存在该包的压缩包，如果存在，就会向远程仓库发送请求，确认是否过期（304 检查），如果没有过期，则直接从缓存中复制到 `node_modules` 目录中。
3. 如果缓存中不存在该包的压缩包，或者过期了，则从远程仓库下载压缩包，并保存（更新）到缓存目录中。
4. 另外根据是否离线或对目标仓库失去访问权限，npm 还提供了 `fallback-to-offline` 模式，该模式使无法访问远程仓库时直接使用本地缓存。

此外，还提供了新的参数，用户可以置顶缓存使用的策略

* `--prefer-offline`：优先使用缓存，如果缓存不可用，则从远程仓库下载。
* `--prefer-online`：优先从远程仓库下载，并使用重新验证的新鲜数据刷新缓存。
* `--offline`：强制使用缓存，如果缓存不可用，则报错。

### 缓存清理

* `npm cache clean` 命令可以清理缓存目录。
* `npm cache verify` 命令可以验证缓存目录的完整性。


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://coderlzw.gitbook.io/web/npm/npm/npm-huan-cun.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
