更新时间:2023-01-06 09:45:21浏览次数:707+次
在本文中,我将向您展示如何使用Node Version Manager(NVM)在Linux上运行多个版本的Node.js。NVM是一个简单的bash脚本,用于使用您喜爱的Linux终端管理多个活动node.js版本。
如何在Linux上安装Node版本管理器
Node版本管理器项目提供了一个脚本,可以自动执行安装。只需运行以下命令即可安装:
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/master/install.sh|bash
该脚本将nvm存储库克隆到~/.nvm目录,并将以下源代码行添加到您的配置文件中(~/.bash_profile,~/.zshrc,~/.profile或~/.bashrc):
export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh" # This loads nvm
[ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion" # This loads nvm bash_completion
如果您是zsh用户,请将这些行添加到~/.zshrc文件中。
要验证是否已安装nvm,请执行以下操作:
$ source ~/.bashrc
$ command -v nvm
nvm
如果安装成功,则应输出“nvm”。
相关可参考在Ubuntu 22.04系统上安装Node.js和npm的三种方法,链接地址在https://www.hmxthome.com/linux/4833.html
如何使用nvm管理Node.js版本
现在您已经安装了nvm,让我们看看如何使用它来管理系统上安装的Node.js版本。
1、检查Node.js的可用版本
检查可安装的版本:
$ nvm ls-remote
v12.22.12 (Latest LTS: Erbium)
v14.19.3 (Latest LTS: Fermium)
v16.15.0 (Latest LTS: Gallium)
v18.13.0
v18.2.0
2、安装Node.js的最新版本
要下载、编译和安装节点的最新版本,请运行:
$ nvm install node
Downloading and installing node v18.13.0...
Downloading https://nodejs.org/dist/v18.13.0/node-v18.13.0-linux-x64.tar.xz
################################### 100.0%
Computing checksum with sha256sum
Checksums matched!
Now using node v18.13.0
Creating default alias: default -> node (-> v18.13.0)
如果是v18.2.0版本,则可手动用https://nodejs.org/dist/v18.2.0/node-v18.2.0-linux-x64.tar.xz链接。
3、安装Node.js的特定版本
安装Node的特定版本,提供版本号作为nvm安装命令的参数:
$ nvm install v16
Downloading and installing node v16.15.0...
Downloading https://nodejs.org/dist/v16.15.0/node-v16.15.0-linux-x64.tar.xz
################################### 100.0%
Computing checksum with sha256sum
Checksums matched!
Now using node v16.15.0 (npm v8.5.5)
$ nvm install v14
Downloading and installing node v14.19.3...
Downloading https://nodejs.org/dist/v14.19.3/node-v14.19.3-linux-x64.tar.xz
################################### 100.0%
Computing checksum with sha256sum
Checksums matched!
Now using node v14.19.3 (npm v6.14.17)
4、安装Node.js LTS版本
这将安装节点的最新LTS版本:
$ nvm install --lts
Downloading and installing node v16.15.0...
Downloading https://nodejs.org/dist/v16.15.0/node-v16.15.0-linux-x64.tar.xz
################################### 100.0%
Computing checksum with sha256sum
Checksums matched!
Now using node v16.15.0 (npm v8.5.5)
5、列出已安装的Node.js版本
要检查已安装的版本,请使用:
$ nvm ls
6、使用最新的Node.js
要在shell上使用最新版本,请运行:
$ nvm use node
如果是v18.13.0版本,则会返回Now using node v18.13.0的信息。
7、使用特定版本的节点
指定版本号:
$ nvm use v16
Now using node v16.15.0 (npm v8.5.5)
8、安装时迁移全局包
如果要安装新版本的Node.js并从以前的版本迁移npm包,比如以下示例:
$ nvm install node --reinstall-packages-from=node
v18.2.0 is already installed.
Now using node v18.2.0 (npm v8.9.0)
Can not reinstall packages from the current version of node.
要使用Node的系统版本,请在使用结束时添加系统:
$ nvm use system
$ nvm run system --version
要恢复PATH,可以禁用它:
nvm deactivate
有关更多用法示例,请访问nvm Github页面,链接地址在https://github.com/nvm-sh/nvm