在 Ubuntu 上配置 Node.js,通常包含安装 Node.js / npm、版本管理(可选)、环境变量与镜像配置、基础项目运行几个部分。下面按常见场景说明。
以 Node.js 20.x 为例:
# 更新系统
sudo apt update
# 安装依赖
sudo apt install -y curl
# 添加 NodeSource 源
curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
# 安装 Node.js
sudo apt install -y nodejs
# 查看版本
node -v
npm -v
sudo apt update
sudo apt install -y nodejs npm
⚠️ Ubuntu 默认源中的 Node 版本通常偏低,不推荐生产使用。
# 安装 NVM
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash
# 重新打开终端或执行
source ~/.bashrc
# 安装 Node
nvm install 20
nvm use 20
nvm alias default 20
npm config set registry https://registry.npmmirror.com
查看配置:
npm config get registry
如果使用系统 Node,建议修改全局目录:
mkdir ~/.npm-global
npm config set prefix '~/.npm-global'
echo 'export PATH=~/.npm-global/bin:$PATH' >> ~/.bashrc
source ~/.bashrc
mkdir demo && cd demo
npm init -y
npm install express
# app.js
const express = require('express')
const app = express()
app.get('/', (req, res) => {
res.send('Hello Node.js')
})
app.listen(3000, () => {
console.log('Server running on http://localhost:3000')
})
运行:
node app.js
npm install -g pm2
pm2 start app.js
pm2 save
pm2 startup
如果你是想:
可以告诉我具体用途,我给你更针对性的配置方案。