在 CentOS 上配置 Node.js 模块,通常分为 安装 Node.js → 使用 npm/yarn 安装模块 → 配置环境变量/镜像源 这几步。下面按常见场景给你一个完整说明。
# 安装依赖
sudo yum install -y curl
# 安装 Node.js 18.x(LTS)
curl -fsSL https://rpm.nodesource.com/setup_18.x | sudo bash -
sudo 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
# 安装 Node.js
nvm install 18
nvm use 18
cd /path/to/project
npm install express
npm install -g pm2
npm config set registry https://registry.npmmirror.com
查看:
npm config get registry
mkdir ~/.npm-global
npm config set prefix ~/.npm-global
编辑 ~/.bashrc 或 ~/.bash_profile:
export PATH=~/.npm-global/bin:$PATH
使配置生效:
source ~/.bashrc
✅ 不要用 sudo npm install -g
✅ 推荐用 nvm 或 自定义 prefix
安装编译工具:
sudo yum groupinstall -y "Development Tools"
sudo yum install -y gcc gcc-c++ make openssl-devel
npm install -g yarn
yarn config set registry https://registry.npmmirror.com
# 安装 Node.js
curl -fsSL https://rpm.nodesource.com/setup_18.x | sudo bash -
sudo yum install -y nodejs
# 配置镜像
npm config set registry https://registry.npmmirror.com
# 项目初始化
mkdir myapp && cd myapp
npm init -y
npm install express
| 场景 | 建议 |
|---|---|
| 服务器 | NodeSource + npm |
| 开发环境 | NVM |
| 国内网络 | 配置 npmmirror |
| 全局模块 | 自定义 prefix |
| 旧 CentOS | EPEL |
如果你有 具体报错信息、CentOS 版本(7/8/Stream) 或 要配置的模块名称,可以贴出来,我可以针对你的情况一步步排错。