先卸载旧的版本$sudo apt autoremove nodejs 然后$sudo apt autoremove npm
想安装什么版本可以看下官方的node与npm版本依赖关系。Previous Releases | Node.js (nodejs.org)
Node.js Version | Codename | Release Date | npm | |
---|---|---|---|---|
v21.3.0 | - | v10.2.4 | ReleasesChangelogDocs | |
v20.10.0 | Iron | v10.2.3 | ReleasesChangelogDocs | |
v19.9.0 | - | v9.6.3 | ReleasesChangelogDocs | |
v18.19.0 | Hydrogen | v10.2.3 | ReleasesChangelogDocs | |
v17.9.1 | - | v8.11.0 | ReleasesChangelogDocs | |
v16.20.2 | Gallium | v8.19.4 | ReleasesChangelogDocs | |
v15.14.0 | - | v7.7.6 | ReleasesChangelogDocs | |
v14.21.3 | Fermium | v6.14.18 | ReleasesChangelogDocs | |
v13.14.0 | - | v6.14.4 | ReleasesChangelogDocs | |
v12.22.12 | Erbium | v6.14.16 | ReleasesChangelogDocs | |
v11.15.0 | - | v6.7.0 | ReleasesChangelogDocs | |
v10.24.1 | Dubnium | v6.14.12 | ReleasesChangelogDocs | |
v9.11.2 | - | v5.6.0 | ReleasesChangelogDocs | |
v8.17.0 | Carbon | v6.13.4 | ReleasesChangelogDocs | |
v7.10.1 | - | v4.2.0 | ReleasesChangelogDocs | |
v6.17.1 | Boron | v3.10.10 | ReleasesChangelogDocs | |
v5.12.0 | - | v3.8.6 | ReleasesChangelogDocs | |
v4.9.1 | Argon | v2.15.11 | ReleasesChangelogDocs | |
v0.12.18 | - | v2.15.11 | ReleasesChangelogDocs |
下面是官方的操作命令,附上官方链接Nodesource Node.js DEB
sudo apt-get update && sudo apt-get install -y ca-certificates curl gnupg
curl -fsSL https://deb.nodesource.com/gpgkey/nodesource-repo.gpg.key | sudo gpg --dearmor -o /etc/apt/keyrings/nodesource.gpg
NODE_MAJOR=20
echo "deb [signed-by=/etc/apt/keyrings/nodesource.gpg] https://deb.nodesource.com/node_$NODE_MAJOR.x nodistro main" | sudo tee /etc/apt/sources.list.d/nodesource.list
sudo apt-get update && sudo apt-get install nodejs -y
上面这几条命令直接使用会报错,提示gpg: can't create '/etc/apt/keyrings/nodesource.gpg': No such file or directory,很明显的错误了,文件或目录不存在。把路径/etc/apt/keyrings/替换成一个自己本机的路径,然后重新执行上面的命令,过一会儿node就安装成最新版本了。我用命令检测了一下。node -v 显示v20.10.0,npm -v 显示10.2.3已经成功升级到最新的版本。如果想升级到指定的nodejs版本,可以把上面命令行中NODE_MAJOR=20修改成自己想要的版本,例如NODE_MAJOR=18将安装18.X版本的nodejs,好的,先写到这里。