# NVM 管理多版本 Node.js

##### nvm（Node Version Manager）是一个非常有用的工具，可以让您在同一台机器上安装和管理多个 Node.js 版本。

![](https://www.runoob.com/wp-content/uploads/2025/05/1_20ffnM3_eVpgVGGAbpuDjg.png)

### 为什么需要 nvm？

- 不同项目可能需要不同版本的 Node.js
- 测试应用在不同 Node.js 版本下的兼容性
- 方便升级和降级 Node.js 版本

### 安装 nvm

**在 macOS/Linux 上安装 nvm：**

```
# 使用 curl 安装
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.3/install.sh | bash

# 或使用 wget 安装
wget -qO- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.3/install.sh | bash

# 重新加载 shell 配置
source ~/.bashrc
# 或
source ~/.zshrc
```

**在 Windows 上安装 nvm-windows：**

1. 下载 nvm-windows：[https://github.com/coreybutler/nvm-windows/releases](https://github.com/coreybutler/nvm-windows/releases)
2. 下载 nvm-setup.zip
3. 解压并运行安装程序

**nvm 常用命令：**

```
# 查看 nvm 版本
nvm --version

# 列出所有可安装的 Node.js 版本
nvm list-remote
# Windows 上使用
nvm list available

# 安装最新的 LTS 版本
nvm install --lts

# 安装特定版本
nvm install 18.17.0
nvm install 16.20.1

# 列出已安装的版本
nvm list
# 或
nvm ls

# 切换到特定版本
nvm use 18.17.0

# 设置默认版本
nvm alias default 18.17.0

# 查看当前使用的版本
nvm current

# 卸载特定版本
nvm uninstall 16.20.1
```

**实际使用示例：**

```
# 场景：为不同项目使用不同 Node.js 版本

# 项目 A 使用 Node.js 18
cd project-a
nvm use 18.17.0
node --version  # v18.17.0

# 项目 B 使用 Node.js 16
cd ../project-b
nvm use 16.20.1
node --version  # v16.20.1

# 为项目指定 Node.js 版本
echo "18.17.0" > .nvmrc
nvm use  # 自动使用 .nvmrc 中指定的版本
```

### 验证安装是否成功

**创建第一个 Node.js 程序：**

创建一个名为 `hello.js` 的文件：

**实例**

```
// hello.js
console.log('Hello, Node.js!');
console.log('Node.js 版本:', process.version);
console.log('当前工作目录:', process.cwd());
console.log('操作系统:', process.platform);
```

<div class="example" id="bkmrk--1"></div>**预期输出：**

```
Hello, Node.js!
Node.js 版本: v18.17.0
当前工作目录: /Users/username/projects
操作系统: darwin
```

**检查全局安装路径：**

```
# 查看 npm 全局包安装路径
npm config get prefix

# 查看 npm 配置
npm config list

# 查看 Node.js 安装路径
which node
# Windows 上使用
where node
```