温馨提示×

ubuntu怎么运行nodejs

小樊
47
2026-09-06 22:57:12
栏目: 编程语言

在 Ubuntu 上运行 Node.js,一般分 安装运行 两步,下面是最常见、最稳妥的方式。


一、安装 Node.js

方式 1:用 apt(最简单,版本可能不是最新)

sudo apt update
sudo apt install nodejs npm

查看版本:

node -v
npm -v

⚠️ Ubuntu 自带源里的 Node 版本通常较旧


方式 2:用 NodeSource(推荐,版本新)

例如安装 Node 20

curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
sudo apt install -y nodejs

方式 3:用 nvm(适合开发,可切换版本)

curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash
source ~/.bashrc
nvm install 20
nvm use 20

二、运行 Node.js 程序

1️⃣ 写一个简单的测试文件

nano hello.js

内容:

console.log("Hello Node.js");

保存后运行:

node hello.js

2️⃣ 运行一个 Web 服务(示例)

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 程序


如果你告诉我:

  • Ubuntu 版本
  • 是否用于 服务器 / 学习 / 项目
  • 是否要 开机自启

我可以给你更精确的方案(如 systemd 服务)。

0