zoukankan      html  css  js  c++  java
  • node--静态服务器

    1、同步读取文件

    const data = fs.readFileSync('./model/mime.json');
     
    // 这里是添加了可以正常链接其他格式文件的服务器
    const http = require('http')
    const url = require('url')
    const fs = require('fs')
    const path = require('path')
    const mimeModel = require('./model/getmimefromfile')
    
    http.createServer((req, res) => {
      // 只取路径,不要后面的查询字符串
      let pathName = url.parse(req.url).pathname
    
      // 过滤无效请求
      if (pathName === '/') {
        //默认加载首页
        pathName = '/index.html'
      }
    
      //获取文件后缀名
      const extname = path.extname(pathName)
    
      if (pathName !== '/favicon.ico') {
        // 文件操作引入static下的相应文件
    
        //静态托管文件
        fs.readFile('static/' + pathName, (err, data) => {
          if (err) {
            // 错误处理
            fs.readFile('static/404.html', (err, data) => {
              res.writeHead(200, {
                'Content-Type': "text/html;charset=utf8"
              })
              res.write(data)
              res.end()
            })
          } else {
            // 记得设置相应头
            let mime = mimeModel.getMime(fs, extname)
            console.log(mime)
            res.writeHead(200, {
              "Content-Type": mime + ";charset='utf8'"
            })
            res.write(data)
            res.end()
          }
        })
      }
    }).listen(8080, () => {
      console.log('server is running')
    })
  • 相关阅读:
    CSS的三种定位方式介绍(转载)
    CSS背景颜色透明
    去除网页滚动条的方法
    es6
    Android复习
    caculater
    字符流
    字节流
    File类
    泛型继承
  • 原文地址:https://www.cnblogs.com/Tanqurey/p/11143929.html
Copyright © 2011-2022 走看看