实例3 上面有点回调,优化成近似同步的写法
route.js
const fs =require('fs') const promisify = require('util').promisify; const stat = promisify(fs.stat) const readdir = promisify(fs.readdir); module.exports=async function(req,res,filePath){ try{ const stats =await stat(filePath) if(stats.isFile()){ res.statusCode = 200 res.setHeader('content-Type','text/plain') fs.createReadStream(filePath).pipe(res); // fs.readFile(filePath,(err,data)=>{ // res.end(data) // }); }else if(stats.isDirectory()){ //所有异步调用必须用await const files =await readdir(filePath); res.statusCode = 200 res.setHeader('content-Type','text/plain') res.end(files.join(',')); } }catch(ex){ console.error(ex); res.statusCode = 404 res.setHeader('content-Type','text/plain') res.end(`${filePath} is not a directory or file ${ex.error}`) } }
app.js
const http = require('http'); const chalk = require('chalk') const path = require('path') const conf = require('./config/defaultConfig.js'); const route = require('./config/helper/route') const server = http.createServer((req,res)=>{ const url = req.url; //拿到文件路径 const filePath = path.join(conf.root,req.url) route(req,res,filePath) }); server.listen(conf.port,conf.hostname,()=>{ const addr = `http://${conf.hostname}:${conf.port}`; console.log(`Server started at ${chalk.green(addr)}`); })