温馨提示×

新手如何配centos nodejs

小樊
47
2026-09-08 21:01:35
栏目: 编程语言

下面是新手在 CentOS 上配置 Node.js 的最常用、最稳妥做法(以 CentOS 7 / 8 / Stream 为例,含常见坑)。


一、先更新系统(建议)

sudo yum update -y

如果是 CentOS 8 / Stream:

sudo dnf update -y

二、三种常见安装方式(推荐第 2 种)

✅ 方式一(推荐):用 NodeSource 安装指定版本

适合新手,版本新、稳定。

1. 安装依赖

sudo yum install -y curl

2. 添加 Node.js 源(以 18.x 为例)

curl -fsSL https://rpm.nodesource.com/setup_18.x | sudo bash -

想装 20.x 就改成 setup_20.x

3. 安装 Node.js

sudo yum install -y nodejs

4. 验证

node -v
npm -v

✅ 方式二:用 EPEL(版本较旧,不推荐新手)

sudo yum install -y epel-release
sudo yum install -y nodejs npm

⚠️ CentOS 自带版本通常很老(如 10.x)


✅ 方式三:用 NVM(适合开发/多版本)

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(新手建议做)

1. 修改 npm 镜像(国内更快)

npm config set registry https://registry.npmmirror.com

2. 查看配置

npm config get registry

四、开放防火墙(如跑 Web 服务)

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


如果你愿意,告诉我:

  • CentOS 版本
  • 用来干嘛(学习 / 服务器 / 前端 / 后端)

我可以直接给你一套最合适方案

0