下面按常见使用场景给你讲一下在 Ubuntu 上配置 Node.js 的几种方式,从“最推荐”到“可选”。
sudo apt update
sudo apt upgrade -y
sudo apt install -y curl software-properties-common
curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
想装 18:
setup_18.x
想装 22:setup_22.x
sudo apt install -y nodejs
node -v
npm -v
sudo apt update
sudo apt install -y nodejs npm
⚠️ 版本通常较旧(如 12 / 14)
适合开发环境
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash
source ~/.bashrc
nvm install 20
nvm use 20
nvm alias default 20
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
mkdir test && cd test
npm init -y
echo "console.log('Hello Node')" > index.js
node index.js
node: command not foundsource ~/.bashrcsudo setcap cap_net_bind_service=+ep $(which node)
pm2npm i -g pm2
pm2 start index.js
如果你愿意,可以告诉我:
20.04 / 22.04 / 24.04)我可以给你一套完整部署方案。