在 Ubuntu 上使用 Node.js,一般分安装 → 运行 → 开发三步。下面给你一个实用入门指南。
sudo apt update
sudo apt install nodejs npm
查看版本:
node -v
npm -v
例如安装 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 Ubuntu Node.js");
运行:
node hello.js
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 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
lsof -i:3000
不要用 sudo npm,建议用 nvm。
pm2 startup
pm2 save
如果你告诉我:
我可以给你更具体的配置方案。