在 CentOS 上搭建 Node.js 环境,常见有 三种方式:
1️⃣ 用系统 yum 安装(最简单,版本旧)
2️⃣ 用 NodeSource 仓库(推荐,版本新)
3️⃣ 用 nvm 管理多版本(开发推荐)
下面分别说明。
sudo yum install -y nodejs npm
node -v
npm -v
⚠️ CentOS 7 默认 Node 版本很老(v6 / v8),不建议。
以 Node.js 18 为例:
curl -fsSL https://rpm.nodesource.com/setup_18.x | sudo bash -
sudo yum install -y nodejs
验证:
node -v
npm -v
✅ 适合服务器生产环境
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash
重新登录或执行:
source ~/.bashrc
nvm install 18
nvm use 18
node -v
nvm alias default 18
✅ 可随时切换 Node 版本
npm config set registry https://registry.npmmirror.com
mkdir ~/.npm-global
npm config set prefix '~/.npm-global'
export PATH=~/.npm-global/bin:$PATH
请升级到 CentOS 7+
如果你告诉我:
我可以给你最合适的一套配置方案。