Skip to content

Node.js 动静分离

动静分离是将静态资源(HTML/CSS/JS/图片)与动态内容(API 请求)分开处理,提升性能和可伸缩性。

优势

  • 性能优化 — 静态资源可缓存(CDN / 浏览器),减少网络开销
  • 负载均衡 — 动态请求分发到不同服务,平衡压力
  • 安全性 — 静态资源公开访问,动态请求独立做认证授权

实现方案

  • Nginx/Apache 反向代理转发(生产环境主流)
  • CDN 分发静态资源
  • Node.js 自建服务器区分处理(用于学习/小型项目)

Node.js 代码实现

js
import http from 'node:http'
import fs from 'node:fs'
import path from 'node:path'
import mime from 'mime'

const server = http.createServer((req, res) => {
  const { url, method } = req

  // 处理静态资源
  if (method === 'GET' && url.startsWith('/static')) {
    const filePath = path.join(process.cwd(), url)
    const mimeType = mime.getType(filePath)

    fs.readFile(filePath, (err, data) => {
      if (err) {
        res.writeHead(404, { 'Content-Type': 'text/plain' })
        return res.end('Not Found')
      }
      res.writeHead(200, {
        'Content-Type': mimeType,
        'Cache-Control': 'public, max-age=3600',  // 强缓存 1 小时
      })
      res.end(data)
    })
  }

  // 处理动态 API
  if ((method === 'GET' || method === 'POST') && url.startsWith('/api')) {
    // ...业务逻辑
  }
})

server.listen(80)

mime 库

静态文件类型繁多(.html, .css, .js, .png, .mp4...),mime 库可自动通过文件后缀识别 MIME 类型:

js
import mime from 'mime'
mime.getType('./style.css')   // 'text/css'
mime.getType('./logo.png')    // 'image/png'

常见 MIME 类型

类型MIME
HTMLtext/html
CSStext/css
JStext/javascript
JSONapplication/json
PNGimage/png
JPEGimage/jpeg
SVGimage/svg+xml
MP4video/mp4
PDFapplication/pdf
ZIPapplication/zip