在没有安装 NVM 的服务器环境中(如 Docker、CI/CD、虚拟机等),建议使用 Node.js 官方的二进制包源(PPA)来快速安装特定版本的 Node.js。本指南将展示如何在 Ubuntu/Debian 系统中通过 NodeSource 官方 PPA 安装 Node.js 的 LTS 与最新版本。
适合最新项目开发和维护:
# 1. 添加 NodeSource 源
curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
# 2. 安装 Node.js 20
sudo apt-get install -y nodejs
# 3. 验证安装
node -v
npm -v
适合已有系统兼容性较好的 LTS 项目:
# 1. 添加 NodeSource 源
curl -fsSL https://deb.nodesource.com/setup_18.x | sudo -E bash -
# 2. 安装 Node.js 18
sudo apt-get install -y nodejs
# 3. 验证安装
node -v
npm -v
适合旧系统或历史项目兼容需求:
# 1. 添加 NodeSource 源
curl -fsSL https://deb.nodesource.com/setup_16.x | sudo -E bash -
# 2. 安装 Node.js 16
sudo apt-get install -y nodejs
# 3. 验证安装
node -v
npm -v
适合测试新特性、前沿技术栈:
# 1. 添加 NodeSource 源
curl -fsSL https://deb.nodesource.com/setup_22.x | sudo -E bash -
# 2. 安装 Node.js 22
sudo apt-get install -y nodejs
# 3. 验证安装
node -v
npm -v
安装 curl
工具(如未安装):
sudo apt-get update
sudo apt-get install -y curl
安装新版本时,若系统中存在旧的 nodejs
或 libnode
依赖,可能出现如下错误:
dpkg: error processing archive nodejs_xxx.deb (--unpack):
trying to overwrite '/usr/share/systemtap/tapset/node.stp',
which is also in package libnode72:amd64 ...
解决方案:先卸载旧版本的相关依赖
sudo apt-get remove --purge nodejs libnode72
sudo apt-get autoremove
然后重新安装:
sudo apt-get install -y nodejs
Dockerfile
中使用官方 Node 镜像(如 node:20
、node:18
等)。npm
版本也是最新,可使用 npm install -g npm
升级。