在 Ubuntu 下“设置 Node.js”通常涉及安装、版本管理、环境变量和镜像配置。下面按常见场景给你一份清晰指南。
# 以 Node.js 20.x 为例
curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
sudo apt install -y nodejs
验证:
node -v
npm -v
sudo apt update
sudo apt install nodejs npm
⚠️ Ubuntu 自带版本通常偏旧,不建议生产使用
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
查看:
npm config get registry
mkdir ~/.npm-global
npm config set prefix ~/.npm-global
编辑 ~/.bashrc:
export PATH=~/.npm-global/bin:$PATH
生效:
source ~/.bashrc
✅ 不要用 sudo npm
✅ 用 nvm 或上面“全局路径”方案
npm config set proxy http://127.0.0.1:7890
npm config set https-proxy http://127.0.0.1:7890
node -e "console.log('Node.js OK')"
如果你是指 系统服务 / PM2 / Docker / 生产部署,告诉我你的使用场景,我可以给你更具体的配置方案。