基于Node.js 搭建静态资源服务器

2,097 阅读1分钟

静态资源服务器

什么是静态资源服务器

静态资源服务器指的是不会被服务器的动态运行所改变或者生成的文件. 它最初在服务器运行之前是什么样子, 到服务器结束运行时, 它还是那个样子. 比如平时写的 js, css, html 文件, 都可以算是静态资源. 那么很容易理解, 静态资源服务器的功能就是向客户端提供静态资源.

解决思路

  • 把所有的静态资源(.html,.png,.css,.js)全放在一个指定的目录里;
  • 收到用户的请求之后,去指定的目录下去找对应的文件
    • 找到,把内容读出来返回给用户。
    • 找不到,报404。

例如:可以把所有的静态资源放到 public 文件夹里面,然后使用 server.js 来启动web服务器 1.jpg

const http = require("http");
const path = require("path");
const fs = require("fs");
// “策略模式”
// .png --> 'image/png'
// .html --> 'text/html;charset=utf8'
// .js --> 'application/javascript;charset=utf8'
// .css --> 'text/css;charset=utf8'
const obj = {
  ".png": "image/png",
  ".jpg": "image/jpg",
  ".html": "text/html;charset=utf8",
  ".js": "application/javascript;charset=utf8",
  ".css": "text/css;charset=utf8",
};

const server = http.createServer((req, res) => {
  // 如果直接http://localhost:8081 ==> req.url 就是 /
  // 默认不写 /index.html 直接访问
  const url = req.url === "/" ? "/index.html" : req.url;
  console.log(url);
  const filePath = path.join(__dirname, "public", url);
  console.log("要读取的文件地址", filePath);
  fs.readFile(filePath, (err, data) => {
    if (err) {
      console.log(12);
      res.statusCode = 404;
      res.end("not found");
    } else {
      // 获取后缀名
      const extName = path.extname(filePath);
      console.log("本次请求的资源", extName, filePath);
      if (obj[extName]) {
        res.setHeader("content-type", obj[extName]);
      }
      res.end(data);
    }
  });
  //res.end(filePath);
});
server.listen(8081, () => {
  console.log("服务已启动");
});