在 CentOS 上配置 Node.js 及其依赖,常见做法有 源码安装、NodeSource 仓库、NVM(推荐) 等。下面从最常用、最稳妥的方式讲起,并包含依赖安装、npm 配置、常见问题处理。
sudo yum install -y curl wget gcc gcc-c++ make
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash
加载环境变量:
source ~/.bashrc
nvm list-remote
nvm install 18
nvm use 18
nvm alias default 18
验证:
node -v
npm -v
✅ 优点
sudo yum install -y curl
curl -fsSL https://rpm.nodesource.com/setup_18.x | sudo bash -
sudo yum install -y nodejs
验证:
node -v
npm -v
✅ 适合
sudo yum install -y nodejs npm
⚠ 版本通常较旧(v10 甚至更低)
cd /path/to/project
npm install
或使用国内镜像:
npm install --registry=https://registry.npmmirror.com
# yarn
npm install -g yarn
yarn install
# pnpm
npm install -g pnpm
pnpm install
npm config set registry https://registry.npmmirror.com
mkdir ~/.npm-global
npm config set prefix ~/.npm-global
echo 'export PATH=~/.npm-global/bin:$PATH' >> ~/.bashrc
source ~/.bashrc
sudo yum install -y gcc gcc-c++ make python3
建议:
✅ 使用:
npm ci(锁定依赖)npm install -g pm2
pm2 start app.js
如果你愿意,可以告诉我:
我可以给你一套完全贴合你环境的配置方案。