下面按**“在 Linux 上安装并配置 Node.js”**来说明,适用于常见发行版(Ubuntu / Debian / CentOS / 通用 Linux)。
以 Ubuntu / Debian 为例:
# 安装依赖
sudo apt update
sudo apt install -y curl
# 添加 NodeSource(以 Node 20 为例)
curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
# 安装 Node.js
sudo apt install -y nodejs
验证:
node -v
npm -v
Ubuntu / Debian
sudo apt update
sudo apt install nodejs npm
CentOS / Rocky / Alma
sudo yum install nodejs npm
# 安装 nvm
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash
# 重新加载 shell
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
mkdir ~/.npm-global
npm config set prefix '~/.npm-global'
编辑 ~/.bashrc:
export PATH=~/.npm-global/bin:$PATH
生效:
source ~/.bashrc
mkdir demo && cd demo
npm init -y
npm install express
index.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 3000')
})
运行:
node index.js
npm install -g pm2
pm2 start index.js
✅ npm permission denied
→ 使用 nvm 或配置 ~/.npm-global
✅ 端口被占用
lsof -i:3000
✅ 查看 Node 路径
which node
如果你告诉我:
我可以给你更精确的配置方案。