Linux 安装 Node.js
方法一:使用 nvm(推荐)
bash
# 安装 nvm
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash
# 重新加载配置
source ~/.bashrc
# 安装 LTS 版本
nvm install --lts
# 验证
node -v
npm -v方法二:使用 NodeSource 官方仓库
Ubuntu / Debian
bash
# 添加 NodeSource 仓库(Node.js 22.x LTS)
curl -fsSL https://deb.nodesource.com/setup_22.x | sudo -E bash -
# 安装
sudo apt-get install -y nodejs
# 验证
node -v
npm -vCentOS / RHEL / Fedora
bash
# 添加仓库
curl -fsSL https://rpm.nodesource.com/setup_22.x | sudo bash -
# 安装
sudo yum install -y nodejs
# 或 Fedora/RHEL 8+
sudo dnf install -y nodejs方法三:使用系统包管理器
注意
系统包管理器中的 Node.js 版本通常较旧,生产环境建议使用 nvm 或 NodeSource 方式安装。
bash
# Ubuntu/Debian(版本较旧)
sudo apt update && sudo apt install nodejs npm
# Arch Linux(版本较新)
sudo pacman -S nodejs npm配置 npm 镜像
bash
npm config set registry https://registry.npmmirror.com全局包安装目录配置
使用系统包管理器安装时,全局安装包需要 sudo,可通过以下方式解决:
bash
# 创建用户级全局目录
mkdir -p ~/.npm-global
npm config set prefix '~/.npm-global'
# 添加到 PATH
echo 'export PATH=~/.npm-global/bin:$PATH' >> ~/.bashrc
source ~/.bashrc验证安装
bash
node -v # 输出 Node.js 版本
npm -v # 输出 npm 版本
npx -v # 输出 npx 版本常见发行版安装速查
| 发行版 | 推荐方式 |
|---|---|
| Ubuntu 20.04+ | NodeSource 或 nvm |
| Debian 11+ | NodeSource 或 nvm |
| CentOS 7/8 | NodeSource 或 nvm |
| Arch Linux | pacman |
| Alpine Linux | apk add nodejs npm |