Skip to content

动静分离

将动态资源与静态资源分开处理和分发。

资源分类

动态资源

如动态网页、API请求

静态资源

HTML、CSS、JavaScript、图像文件

实现

  • 使用反向代理服务器(如Nginx、Apache)将静态请求和动态请求转发到不同的后端服务器或服务。
  • 将静态资源部署到CDN上,通过CDN分发静态资源,减轻源服务器的负载。
  • 使用专门的静态文件服务器(如Amazon S3、Google Cloud Storage)存储和提供静态资源,而将动态请求交给应用服务器处理。
js
const http = require("http");
const path = require("path");
const fs = require("fs");
const mime = require("mime");

http
  .createServer((req, res) => {
    const { method, url } = req;
    // 静态资源处理都是使用GET方式
    if (method === "GET" && url.startsWith("/static")) {
      const filePath = path.join(process.cwd(), url);

      fs.readFile(filePath, (err, data) => {
        if (err) {
          res.statusCode = 404;
          res.end("Not Found");
        } else {
          console.log("GET static", filePath);
          const type = mime.getType(filePath);
          res.writeHead(200, {
            "Content-Type": type,
            "Cache-Control": "public, max-age=3600",
          });
          res.end(data);
        }
      });
    } else if (url.startsWith("/api")) {
      //动态资源
      res.writeHead(200, { "Content-Type": "application/json" });
      res.end(JSON.stringify({ message: "Hello, World!" }));
    } else {
      // NOT Found
      res.statusCode = 404;
      res.end("Not Found");
    }
  })
  .listen(3000, () => {
    console.log("server is running");
  });