在 Ubuntu 上安装 Node.js
方法一:使用 apt 安装(版本较旧)
sudo apt-get update
sudo apt-get install nodejs
sudo apt-get install npm
方法二:使用 nvm 安装(推荐)
nvm(Node Version Manager)可以管理多个 Node.js 版本。
# 安装 nvm
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash
# 重新加载 shell 配置
source ~/.bashrc
# 安装 Node.js
nvm install 20 # 安装指定版本
nvm install --lts # 安装最新 LTS 版本
nvm use 20 # 切换版本
nvm alias default 20 # 设置默认版本
# 查看已安装版本
nvm ls
# 查看可安装版本
nvm ls-remote
方法三:使用 NodeSource 安装
# 安装 Node.js 20.x
curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
sudo apt-get install -y nodejs
# 验证
node -v
npm -v
升级 Node.js
# 使用 n 升级(需先安装 n)
sudo npm install -g n
sudo n latest # 升级到最新版
sudo n stable # 升级到最新稳定版
sudo n 20.10.0 # 升级到指定版本
# 使用 nvm 升级
nvm install 20
nvm alias default 20
npm 镜像配置
# 查看当前镜像
npm get registry
# 设置淘宝镜像(npmmirror)
npm config set registry https://registry.npmmirror.com/
# 恢复官方镜像
npm config set registry https://registry.npmjs.org/
# 安装 cnpm(可选)
npm install cnpm -g --registry=https://registry.npmmirror.com
卸载
# 使用 apt 卸载
sudo npm uninstall npm -g
sudo apt-get remove nodejs
# 使用 nvm 卸载
nvm uninstall 20
原文链接:https://www.ssssmy.com/notes/zai-ubuntu-shang-an-zhuang-nodejs