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')
})

 

posted on 2019-07-06 19:53  Tanqurey  阅读(179)  评论(0编辑  收藏  举报