# NVM (Node Version Manager) 使用文档 ## 一、什么是 NVM? NVM(Node Version Manager)是一个用于管理多个 Node.js 版本的工具。它可以让你在同一台机器上安装、切换和使用不同版本的 Node.js,非常适合需要兼顾不同项目 Node.js 版本需求的开发者。 --- ## 二、安装 NVM ### 2.1 一键安装 ```bash curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash ``` ### 2.2 加载 NVM 安装完成后,需要重新加载终端或者执行以下命令使 nvm 生效: ```bash export NVM_DIR="$HOME/.nvm" [ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh" [ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion" ``` ### 2.3 验证安装 ```bash nvm --version ``` --- ## 三、配置镜像源(加速 Node.js 下载) 在国内使用 nvm 下载 Node.js 时,建议配置淘宝镜像源以提高下载速度。 ### 临时配置(仅当前会话生效) ```bash export NVM_NODEJS_ORG_MIRROR=https://npmmirror.com/mirrors/node ``` ### 永久配置(写入 shell 配置文件) ```bash echo 'export NVM_NODEJS_ORG_MIRROR=https://npmmirror.com/mirrors/node' >> ~/.bashrc source ~/.bashrc ``` --- ## 四、NVM 常用命令 ### 4.1 安装 Node.js ```bash # 安装最新稳定版 nvm install node # 安装指定版本 nvm install 20.11.0 # 安装最新的 LTS 版本 nvm install --lts ``` ### 4.2 查看可安装的版本 ```bash # 列出所有可安装的版本 nvm ls-remote # 列出所有 LTS 版本 nvm ls-remote --lts ``` ### 4.3 切换 Node.js 版本 ```bash # 使用指定版本 nvm use 20.11.0 # 使用最新稳定版 nvm use node # 使用最新的 LTS 版本 nvm use --lts ``` ### 4.4 查看已安装的版本 ```bash nvm ls ``` ### 4.5 设置默认版本 ```bash # 设置系统默认使用的 Node.js 版本 nvm alias default 20.11.0 # 将最新稳定版设为默认 nvm alias default node ``` ### 4.6 卸载 Node.js 版本 ```bash nvm uninstall 20.11.0 ``` --- ## 五、版本管理实践 ### 5.1 为项目指定 Node.js 版本 在项目根目录创建 `.nvmrc` 文件: ```bash # .nvmrc 文件内容示例 20.11.0 ``` 然后在该目录下运行 `nvm use` 即可自动切换到对应版本。 ### 5.2 查看当前使用的版本 ```bash node -v npm -v ``` ### 5.3 版本别名管理 ```bash # 创建别名 nvm alias myapp 20.11.0 # 使用别名切换 nvm use myapp # 删除别名 nvm unalias myapp ``` --- ## 六、常见问题 ### 6.1 命令找不到(command not found) 如果重启终端后出现 `nvm: command not found`,请确保已将 nvm 加载命令添加到 `~/.bashrc`、`~/.zshrc` 或 `~/.profile` 文件中。 ### 6.2 下载速度慢 配置淘宝镜像源即可解决: ```bash export NVM_NODEJS_ORG_MIRROR=https://npmmirror.com/mirrors/node ``` ### 6.3 权限问题 使用 nvm 安装的 Node.js 不需要 `sudo` 权限,如果遇到权限问题,请检查是否使用了系统自带的 Node.js。 --- ## 七、常用命令速查表 | 命令 | 说明 | |------|------| | `nvm --version` | 查看 nvm 版本 | | `nvm install ` | 安装指定版本 | | `nvm install node` | 安装最新稳定版 | | `nvm install --lts` | 安装最新 LTS 版本 | | `nvm use ` | 切换使用指定版本 | | `nvm ls` | 列出已安装版本 | | `nvm ls-remote` | 列出远程所有版本 | | `nvm alias default ` | 设置默认版本 | | `nvm uninstall ` | 卸载指定版本 | | `nvm current` | 显示当前使用的版本 | --- > 文档版本: v1.0 > 最后更新: 2025年