在 CentOS 下设置 Node.js,常见有几种方式,推荐按你的使用场景选择。下面从最推荐到不推荐依次说明,并给出常用配置示例。
sudo yum remove -y nodejs npm
sudo yum install -y curl
curl -fsSL https://rpm.nodesource.com/setup_18.x | sudo bash -
可选版本:
setup_16.xsetup_20.xsetup_lts.xsudo yum install -y nodejs
node -v
npm -v
✅ 优点:
适合一台机器多个 Node 版本。
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash
重新加载环境:
source ~/.bashrc
nvm install 18
nvm use 18
nvm alias default 18
✅ 优点:
CentOS 自带版本较老:
sudo yum install -y nodejs npm
查看版本:
node -v
⚠️ 缺点:
npm config set registry https://registry.npmmirror.com
查看:
npm config get registry
mkdir ~/.npm-global
npm config set prefix '~/.npm-global'
加入环境变量:
echo 'export PATH=~/.npm-global/bin:$PATH' >> ~/.bashrc
source ~/.bashrc
npm install -g pnpm --registry=https://registry.npmmirror.com
| 项目 | 说明 |
|---|---|
| CentOS 7 | 官方已 EOL,建议用 NodeSource |
| CentOS 8 | 已停止维护,建议迁移 Rocky / Alma |
| 防火墙 | 端口需放行 |
| SELinux | 可能影响端口,必要时关闭 |
node -e "console.log('Node.js is working')"
| 场景 | 推荐方式 |
|---|---|
| 生产服务器 | ✅ NodeSource |
| 开发 / 多版本 | ✅ NVM |
| 临时测试 | yum |
如果你告诉我:
我可以给你一份完全定制化的安装和部署方案。