温馨提示×

ubuntu怎么用nodejs

小樊
38
2026-09-28 01:32:35
栏目: 编程语言

在 Ubuntu 上使用 Node.js,一般分安装 → 运行 → 开发三步。下面给你一个实用入门指南。


一、在 Ubuntu 上安装 Node.js

方法 1:用 apt(最简单,版本可能略旧)

sudo apt update
sudo apt install nodejs npm

查看版本:

node -v
npm -v

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

新建文件:

nano hello.js

写入内容:

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

运行:

node hello.js

三、写一个简单 HTTP 服务

const http = require('http');

const server = http.createServer((req, res) => {
  res.writeHead(200, { 'Content-Type': 'text/plain' });
  res.end('Hello from Node.js\n');
});

server.listen(3000, () => {
  console.log('Server running at http://localhost:3000');
});

运行:

node server.js

浏览器访问:

http://localhost:3000

四、使用 npm(包管理)

初始化项目:

npm init -y

安装依赖:

npm install express

示例:

const express = require('express');
const app = express();

app.get('/', (req, res) => {
  res.send('Hello Express');
});

app.listen(3000);

五、后台运行(常用)

node server.js &

或用 pm2(生产推荐):

sudo npm install -g pm2
pm2 start server.js

六、常见问题

1. 端口被占用

lsof -i:3000

2. 权限问题

不要用 sudo npm,建议用 nvm。

3. 开机自启

pm2 startup
pm2 save

如果你告诉我:

  • 是新系统还是服务器
  • 想做网站 / 脚本 / 工具
  • 是否用于生产环境

我可以给你更具体的配置方案。

0 踩