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/');
  • 相关阅读:
    python爬虫scrapy之登录知乎
    python爬虫scrapy之downloader_middleware设置proxy代理
    python爬虫scrapy之如何同时执行多个scrapy爬行任务
    python爬虫之scrapy的pipeline的使用
    TotoiseSVN使用教程
    Office办公软件各版本下载(一键安装)
    如何彻底卸载系统自带的IE浏览器
    Sublime Text 3使用方法
    计算机常用键盘快捷键
    WordPress TinyMCE 编辑器增强技巧大全
  • 原文地址:https://www.cnblogs.com/zhoulixue/p/15432065.html
Copyright © 2011-2022 走看看