静态服务器

67 阅读1分钟

背景:

在之前的node.js的学习里,我们都是遇到一个文件读取一个文件。

优化:

但是这样太费劲了,所以我们让他变成在地址中输什么就读什么

  response.statusCode = 200;
  response.setHeader("Content-Type", "text/html;charset=utf-8");
  const x = path;
  response.write(fs.readFileSync(`./public${x}`));
  response.end();

但是这样写当输入不存在路径就挂了,因此要处理一下这个异常

try {
    content = fs.readFileSync(`./public/${filePath}`);
  } catch (error) {
    content = "文件名不存在";
    response.statusCode = 404;
  }

在终端里打印出后缀名

const index = filePath.lastIndexOf(".");    //找到最后一个.的下标,具体看MDN
const h = filePath.substring(index);      //将下标作为首字母,具体看MDN
console.log(h);

将setHeader里的解析方式改为相对应的后缀名

// suffix是后缀
  const suffix = filePath.substring(index);
  const fileType = {
    html: "text/html",
    css: "text/css",
    js: "text/javascript",
    png: "image/png",
    jpg: "image/jpeg",
  };
  response.setHeader(
    "Content-Type",
    `${fileType[suffix] || "text/html"};charset=utf-8`
  );

一个功能强大的静态服务器就做好了! GitHub源码链接