在 CentOS 上安裝特定版本的 Node.js 可以通過多種方法實現,其中最常用的是使用 NodeSource 倉庫或 NVM(Node Version Manager)。以下是這兩種方法的詳細步驟:
添加 NodeSource 倉庫
首先,你需要根據所需的 Node.js 版本選擇合適的 NodeSource 倉庫。例如,如果你想安裝 Node.js 14.x,可以使用以下命令:
curl -sL https://rpm.nodesource.com/setup_14.x | sudo bash -
如果你想安裝其他版本,只需將 setup_14.x
替換為相應的版本號,例如 setup_16.x
或 setup_18.x
。
安裝 Node.js
添加倉庫后,你可以使用 yum
命令來安裝 Node.js:
sudo yum install -y nodejs
驗證安裝
安裝完成后,你可以使用以下命令來驗證 Node.js 和 npm 的版本:
node -v
npm -v
NVM 是一個用于管理多個 Node.js 版本的工具,非常適合需要在不同項目中使用不同 Node.js 版本的用戶。
安裝 NVM
你可以使用以下命令來安裝 NVM:
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.1/install.sh | bash
或者使用 wget
:
wget -qO- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.1/install.sh | bash
安裝完成后,你需要重新加載你的 shell 配置文件(例如 .bashrc
或 .zshrc
):
source ~/.bashrc
安裝特定版本的 Node.js
使用 NVM 安裝特定版本的 Node.js 非常簡單。例如,如果你想安裝 Node.js 14.x,可以使用以下命令:
nvm install 14
如果你想安裝其他版本,只需將 14
替換為相應的版本號,例如 16
或 18
。
切換 Node.js 版本
安裝多個版本的 Node.js 后,你可以使用以下命令來切換當前使用的版本:
nvm use 14
驗證安裝
切換到指定版本后,你可以使用以下命令來驗證 Node.js 和 npm 的版本:
node -v
npm -v
通過以上兩種方法,你可以在 CentOS 上輕松安裝和管理特定版本的 Node.js。選擇哪種方法取決于你的具體需求和個人偏好。