在 Ubuntu 上运行 Node.js,一般分 安装 和 运行 两步,下面是最常见、最稳妥的方式。
sudo apt update
sudo apt install nodejs npm
查看版本:
node -v
npm -v
⚠️ Ubuntu 自带源里的 Node 版本通常较旧
例如安装 Node 20:
curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
sudo apt install -y nodejs
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash
source ~/.bashrc
nvm install 20
nvm use 20
nano hello.js
内容:
console.log("Hello Node.js");
保存后运行:
node hello.js
const http = require('http');
http.createServer((req, res) => {
res.end('Hello from Node.js');
}).listen(3000, () => {
console.log('Server running on port 3000');
});
运行:
node server.js
浏览器访问:
http://localhost:3000
node server.js &
或使用:
nohup node server.js &
✅ 命令不存在 → 没装或 PATH 有问题
✅ 端口被占用 → 改端口或 lsof -i:3000
✅ 权限问题 → 不要用 sudo 跑普通 node 程序
如果你告诉我:
我可以给你更精确的方案(如 systemd 服务)。