zoukankan      html  css  js  c++  java
  • [nodejs] 静态资源服务器

    1. 工具函数

    module/file.js

    读取文件数据

    const fs = require('fs');
    
    const readFile = (path) => new Promise((resolve) => {
      fs.readFile(path, (err, data) => {
        resolve({ err, data });
      });
    });
    
    module.exports = {
      readFile,
    };

    module/util.js

    根据请求路径获取mimeType

    const path = require('path');
    const file = require('./file');
    
    const getMimeType = async (url) => {
      let extname = path.extname(url);
      extname = extname.split('.').slice(-1).toString();
      const { err, data } = await file.readFile('./module/mime.json');
      const mimeTypeMap = err ? {} : JSON.parse(data);
      return mimeTypeMap[extname] || 'text/plain';
    }
    module.exports = {
      getMimeType,
    };

    module/mime.json

    下载地址: https://github.com/micnic/mime.json/blob/master/index.json

    2.静态路由处理函数

    router/index.js

    const file = require('../module/file');
    const util = require('../module/util');
    
    const static = async (req, res, staticPath = 'static') => {
      const { url } = req;
      if (url !== '/favicon.ico') {
        const filePath = `${staticPath}${url}`;
        const { err, data } = await file.readFile(filePath);
        if (!err) {
          const mimeType = await util.getMimeType(url);
          res.writeHead(200, { 'Content-Type': mimeType });
          res.end(data);
        }
      }
    }
    module.exports = {
      static,
    };

    3. sever.js

    const http = require('http');
    const router = require('./router/index');
    
    http.createServer(async (req, res) => {
      await router.static(req, res); // 静态资源服务器
    
      const { url } = req;
      if (url === '/index') {
        res.writeHead(200, { 'Content-Type': 'application/json' });
        res.end(JSON.stringify({ a: 1, b: 2 }));
      } else if (url === 'login') {
        res.writeHead(200, { 'Content-Type': 'application/json' });
        res.end(JSON.stringify({ a: 2, b: 3 }));
      } else {
        res.writeHead(200, { 'Content-Type': 'text/plain' });
        res.end('404 page not found.');
      }
    }).listen(3000);
    
    console.log('Server running at http://127.0.0.1:3000/');
  • 相关阅读:
    Spring Boot全日志设置
    SpringBoot整合Quartz
    Kubernetes网络方案的三大类别和六个场景
    微服务化之缓存的设计
    金融创新业务基于容器云的微服务化实践
    致传统企业朋友:不够痛就别微服务,有坑 (1)
    致传统企业朋友:不够痛就别微服务,有坑 (2)
    The Beam Model:Stream & Tables翻译(上)
    细说Mammut大数据系统测试环境Docker迁移之路
    [译] 关于 SPA,你需要掌握的 4 层 (1)
  • 原文地址:https://www.cnblogs.com/zhoulixue/p/15432065.html
Copyright © 2011-2022 走看看