Ubuntu 安装 Node.js 指定版本指南

发布于:2025-05-21 ⋅ 阅读:(27) ⋅ 点赞:(0)

Ubuntu 安装 Node.js 指定版本指南(适用于生产与开发环境)

在没有安装 NVM 的服务器环境中(如 Docker、CI/CD、虚拟机等),建议使用 Node.js 官方的二进制包源(PPA)来快速安装特定版本的 Node.js。本指南将展示如何在 Ubuntu/Debian 系统中通过 NodeSource 官方 PPA 安装 Node.js 的 LTS 与最新版本。


一、安装 Node.js 20(当前活跃 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

二、安装 Node.js 18(长期支持版本 LTS)

适合已有系统兼容性较好的 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

三、安装 Node.js 16(维护阶段的旧 LTS)

适合旧系统或历史项目兼容需求:

# 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

四、安装 Node.js 22(当前最新版,非 LTS)

适合测试新特性、前沿技术栈:

# 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

六、常见问题及解决方法

问题 1:Node.js 安装冲突

安装新版本时,若系统中存在旧的 nodejslibnode 依赖,可能出现如下错误:

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

七、其它建议

  • 如果你希望在多个项目中灵活切换 Node.js 版本,建议使用 nvm
  • 若用于 Docker 构建,可直接在 Dockerfile 中使用官方 Node 镜像(如 node:20node:18 等)。
  • 确保安装完后配套的 npm 版本也是最新,可使用 npm install -g npm 升级。

参考资料

在这里插入图片描述


网站公告

今日签到

点亮在社区的每一天
去签到