引入模板引擎(handlebars)
cnpm i handlebars
结构大概是这样子的,新建模板dir.tpl文件和route.js
dir.tpl
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>{{title}}</title> </head> <body> {{#each files}} <a href="{{../dir}}/{{this}}">{{this}}</a> {{/each}} </body> </html>
route.js
const fs =require('fs') const path = require('path') const Handlebars = require('handlebars') const promisify = require('util').promisify; const stat = promisify(fs.stat) const readdir = promisify(fs.readdir); const config = require('../config/defaultConfig') const tplPath = path.join(__dirname,'../template/dir.tpl') const source = fs.readFileSync(tplPath); const template = Handlebars.compile(source.toString()) 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/html') const dir = path.relative(config.root,filePath) const data = { title:path.basename(filePath), // dir:config.root, dir:dir?`/${dir}`:'', files } res.end(template(data)); } }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('./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)}`); })