> ## Content Index
> Fetch the complete content index at: https://djdog.cc/llms.txt
> Use this file to discover other available public pages before exploring further.

# 使用 NVM 管理多个版本的 Node.js 以及配套的 NPM
- URL: https://djdog.cc/blog/2023/nvm/
- Published: 2023-07-06T13:38:02.000Z
- Updated: 2023-07-06T13:38:02.000Z
- Description: NVM 是 Node.js 版本管理工具，可以很便捷地通过命令行快速安装和使用不同版本的Node。
- Author: DJDOG
- Tags: 开发工具, #toc

我们可能在工作和学习中可能都会遇到需要使用多个node版本的时候，NVM可以很好地解决这个问题。[NVM](https://github.com/nvm-sh/nvm?ref=djdog.cc) 全称 node.js version management ，是开源的 nodejs 版本管理工具。通过它我们就可以很便捷地通过命令行快速安装和使用不同版本的 Node。

## 安装

如果现在电脑上有安装 node，切记把它卸载掉。如果是 Windows 系统且有配置过环境变量，记得把环境变量一起删掉。

卸载结束后，用下面的命令安装：

Windows：

```powershell
winget install 'NVM for Windows'

```

Linux：

```bash
export NVM_DIR="$HOME/.nvm" && (
  git clone https://github.com/nvm-sh/nvm.git "$NVM_DIR"
  cd "$NVM_DIR"
  git checkout `git describe --abbrev=0 --tags --match "v[0-9]*" $(git rev-list --tags --max-count=1)`
) && \. "$NVM_DIR/nvm.sh"

```

等待下载结束后自动安装。然后添加环境变量，这里就不作教程了。

然后运行：

```powershell
nvm version

```

如果出现了版本号，则表示安装成功。

然后将下面的代码加入到你的 `~/.bashrc`、`~/.profile`或`~/.zshrc`中：

```bash
export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"
[ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion"

```

## 使用

要下载、编译和安装最新版本的node，请执行以下命令，会自动安装最新的`node`和它对应版本的`npm`：

```bash
nvm install node # "node" 是最新版本的别名

```

要是需要某一个版本的`node`，则运行：

```bash
nvm install <version> # 将其替换成你所需要的版本号

```

卸载指定版本，语法与 `install` 用法一致：

```bash
nvm uninstall <version>

```

切换使用指定的版本 `node`：

```bash
nvm use <version> # 临时,只在当前窗口生效指定版本

nvm alias default <version> # 永久,所有窗口生效指定版本

```

## 使用国内 npm 镜像加速下载

出于众所周知的原因~~GFW~~，国内使用 `npm` 下载的速度可能不是很快，可以使用 [cnpm](https://npmmirror.com/?ref=djdog.cc) 来解决：

```bash
npm install -g cnpm --registry=https://registry.npmmirror.com

```

或者你直接通过添加 `npm` 参数 alias 一个新命令:

```bash
alias cnpm="npm --registry=https://registry.npmmirror.com \
--cache=$HOME/.npm/.cache/cnpm \
--disturl=https://npmmirror.com/mirrors/node \
--userconfig=$HOME/.cnpmrc"

# Or alias it in .bashrc or .zshrc
$ echo '\n#alias for cnpm\nalias cnpm="npm --registry=https://registry.npmmirror.com \
  --cache=$HOME/.npm/.cache/cnpm \
  --disturl=https://npmmirror.com/mirrors/node \
  --userconfig=$HOME/.cnpmrc"' >> ~/.zshrc && source ~/.zshrc

```