在 CentOS 上配置 Node.js 环境,常见且推荐的方式有以下几种。下面按从简单到灵活的顺序说明,你可以根据需求选择。
适合:生产环境 / 需要指定 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_22.xsudo yum install -y nodejs
node -v
npm -v
适合:快速测试 / 不要求新版本
sudo yum install -y epel-release
sudo yum install -y nodejs npm
查看版本:
node -v
⚠ 通常版本较老,不推荐生产环境使用
适合:多版本切换 / 本地开发
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
node -v
npm -v
npm config set registry https://registry.npmmirror.com
查看:
npm config get registry
如果运行 Node 服务(如 3000 端口):
sudo firewall-cmd --add-port=3000/tcp --permanent
sudo firewall-cmd --reload
npm install -g pm2
pm2 start app.js
pm2 save
pm2 startup
| 场景 | 推荐方式 |
|---|---|
| 生产环境 | NodeSource |
| 本地开发 | NVM |
| 快速测试 | EPEL |
如果你愿意,可以告诉我:
我可以给你一套完整部署方案。