下面给你一份在 CentOS 上安装并配置 Node.js 的完整做法,从官方推荐方式到常见配置,适合服务器环境。
sudo yum remove -y nodejs npm
sudo yum install -y curl gcc-c++ make
可替换
18为20、16等
curl -fsSL https://rpm.nodesource.com/setup_18.x | sudo bash -
sudo yum install -y nodejs
node -v
npm -v
✅ 正常示例:
v18.19.0
9.6.7
npm config set registry https://registry.npmmirror.com
查看:
npm config get registry
mkdir -p ~/.npm-global
npm config set prefix '~/.npm-global'
加入环境变量:
echo 'export PATH=~/.npm-global/bin:$PATH' >> ~/.bashrc
source ~/.bashrc
如果你一台机器需要多个 Node.js 版本,推荐 nvm。
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 服务对外访问:
sudo firewall-cmd --add-port=3000/tcp --permanent
sudo firewall-cmd --reload
npm install -g pm2
pm2 start app.js
pm2 save
pm2 startup
which node
echo $PATH
npm config set registry https://registry.npmmirror.com
| 场景 | 推荐方式 |
|---|---|
| 服务器生产环境 | NodeSource + pm2 |
| 本地开发 | nvm |
| 国内服务器 | npm 镜像 |
如果你愿意,可以告诉我:
我可以给你针对性完整配置方案。