text: const fs = require('fs')
  const {join,basename,relative} = require('path')
  const {promisify} = require('util')
  const stat = promisify(fs.stat)
  const readdir = promisify(fs.readdir)
  const pug = require('pug')
  const mime = require('./mime')
  const compress = require('./compress')
  const range = require('./range')
  const isFresh = require('./cache')
  
  const pugPath = join(__dirname,'../views/template.pug')
  const source = fs.readFileSync(pugPath)
  const template = pug.compile(source.toString())
  
  module.exports = async function (req,res,filePath,config) {
    try{
      const stats =await stat(filePath)
      if(stats.isFile()){
        const contentType = mime(filePath)
        res.setHeader('Content-Type',contentType)
  
        if(isFresh(stats,req,res)){
          res.statusCode = 304
          res.end()
          return;
        }
  
        //压缩文件
        let rs;
        const {code,start,end} = range(stats.size,req,res)
        res.statusCode = code
        if (code === 200) {
          rs = fs.createReadStream(filePath);
        }else{
          rs = fs.createReadStream(filePath,{start,end});
        }
        //rs = fs.createReadStream(filePath);
        if(filePath.match(config.compress)){
          rs = compress(rs,req,res)
        }
        rs.pipe(res);
      }else if(stats.isDirectory()){
        const files =await readdir(filePath)
        res.statusCode = 200
        res.setHeader('Content-Type','text/html')
        const dir = relative(config.root,filePath)
        const data = {
          files:files.map(file=>({
            file,
            icon:mime(file)
          })),
          dir:dir?`/${dir}`:'',
          title:basename(filePath)
        }
        res.end(template(data))
      }
    }catch(err){
      if(err){
        console.error(err)
        res.statusCode = 404;
        res.setHeader('Content-Type','text/plain');
        res.end(`${filePath} is not a directory or file`);
        return;
      }
    }
  }
  