下面是新手在 CentOS 上配置 Node.js 的最常用、最稳妥做法(以 CentOS 7 / 8 / Stream 为例,含常见坑)。
sudo yum update -y
如果是 CentOS 8 / Stream:
sudo dnf update -y
适合新手,版本新、稳定。
sudo yum install -y curl
curl -fsSL https://rpm.nodesource.com/setup_18.x | sudo bash -
想装 20.x 就改成
setup_20.x
sudo yum install -y nodejs
node -v
npm -v
sudo yum install -y epel-release
sudo yum install -y nodejs npm
⚠️ CentOS 自带版本通常很老(如 10.x)
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash
source ~/.bashrc
nvm install 18
nvm use 18
✅ 适合一台机器多个 Node 版本
npm config set registry https://registry.npmmirror.com
npm config get registry
sudo firewall-cmd --permanent --add-port=3000/tcp
sudo firewall-cmd --reload
mkdir test && cd test
npm init -y
app.js:
const http = require('http');
http.createServer((req, res) => {
res.end('Hello CentOS Node.js');
}).listen(3000, () => {
console.log('Server running on 3000');
});
运行:
node app.js
浏览器访问:http://服务器IP:3000
❌ node: command not found
→ 重开终端或 source ~/.bashrc
❌ 权限问题
→ 不要用 sudo npm install,用 nvm 或加 --prefix
如果你愿意,告诉我:
我可以直接给你一套最合适方案。