文档
Node.js HTTP 服务器入门
目标
使用 Node.js 内置 http 模块和 fs 模块,创建最简单的 Web 服务器,并实现文件读写演示。
完整代码
// server.js
const http = require('http');
const fs = require('fs');
const path = require('path');
const PORT = 3000;
const DATA_FILE = path.join(__dirname, 'data.json');
// 初始化数据文件
if (!fs.existsSync(DATA_FILE)) {
fs.writeFileSync(DATA_FILE, JSON.stringify({ visits: 0, messages: [] }, null, 2));
}
const server = http.createServer((req, res) => {
const { method, url } = req;
// 路由: GET / — 返回欢迎页
if (method === 'GET' && url === '/') {
const data = JSON.parse(fs.readFileSync(DATA_FILE, 'utf-8'));
data.visits++;
fs.writeFileSync(DATA_FILE, JSON.stringify(data, null, 2));
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
res.end(`
<h1>🎉 Node.js 服务器运行中</h1>
<p>累计访问次数:<strong>${data.visits}</strong></p>
<p>消息数量:${data.messages.length}</p>
<a href="/api/messages">查看消息 API</a>
`);
}
// 路由: GET /api/messages — 返回 JSON
else if (method === 'GET' && url === '/api/messages') {
const data = JSON.parse(fs.readFileSync(DATA_FILE, 'utf-8'));
res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
res.end(JSON.stringify({ success: true, ...data }));
}
// 路由: POST /api/messages — 新增消息
else if (method === 'POST' && url === '/api/messages') {
let body = '';
req.on('data', chunk => (body += chunk));
req.on('end', () => {
const data = JSON.parse(fs.readFileSync(DATA_FILE, 'utf-8'));
const { text } = JSON.parse(body);
data.messages.push({ id: Date.now(), text, time: new Date().toISOString() });
fs.writeFileSync(DATA_FILE, JSON.stringify(data, null, 2));
res.writeHead(201, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ success: true, message: '已添加' }));
});
}
// 404
else {
res.writeHead(404, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'Not Found' }));
}
});
server.listen(PORT, () => {
console.log(`🚀 服务器已启动: http://localhost:${PORT}`);
});
运行步骤
node server.js
# 浏览器访问 http://localhost:3000
# 测试 POST: curl -X POST http://localhost:3000/api/messages -H "Content-Type: application/json" -d '{"text":"Hello Node.js"}'
预期输出
- 浏览器显示欢迎页,含访问计数
GET /api/messages返回 JSON 消息列表POST /api/messages新增消息,data.json 文件实时更新