用 Node 原生 http 模块写一个服务,和用 Express/Koa 比有什么差异?
http 原生模块只提供底层请求/响应对象,路由、body 解析、中间件全要自己写:
import http from 'http'
const server = http.createServer((req, res) => {
if (req.method === 'GET' && req.url === '/api') {
res.writeHead(200, { 'Content-Type': 'application/json' })
res.end(JSON.stringify({ ok: true }))
} else {
res.statusCode = 404
res.end('Not Found')
}
})
server.listen(3000)对比框架:
- Express:基于回调的中间件队列(
app.use),生态最大,但洋葱模型不彻底 - Koa:基于 async 的中间件洋葱模型,用
ctx统一封装 req/res,更轻、更现代 - 原生胜在零依赖、可控性高、性能略好;缺点是样板代码多、安全(防注入/限流)需自实现
选型:内部小工具可原生;业务服务用 Express/Koa/Fastify 提升效率,Fastify 在性能上更优。