<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Index of {{title}}</title>
</head>
<body>
<h1>Index of {{title}}</h1>
<ul>
<li><a href="/">Parent Directory</a></li>
{{each files}}
<li><a href="{{$value}}">{{$value}}</a></li>
{{/each}}
</ul>
</body>
</html>
//引入模块
const http=require('http');
const path=require('path');
const fs=require('fs');
const url=require('url');
const template=require('art-template');
//开启服务
const app=http.createServer();
app.listen(80,()=>console.log('服务器已连接'));
//默认路径
const filePath=path.join(__dirname,'www');
//请求处理
app.on('request', (req,res)=>{
//获取路径
console.log(req.url);
let {pathname,query}=url.parse(req.url,true);
let filePath2=filePath;
if(pathname!='/'){
filePath2=path.join(filePath2,pathname);
}
//获取后缀用以判断
let fileEnd=path.extname(filePath2);
if(fileEnd==''){
//打开文件夹
let data= fs.readFileSync(__dirname+'/apache.html',(err,data)=>data);//apache.html是模板
let files= fs.readdirSync(filePath2,(err,data)=>data);
//把数据代入模板
let html=template.render(data.toString(),{
title:pathname,
files:files
})
res.end(html);
} else {
//打开文件
res.writeHeader(200,{'Content-Type':'text/html; charset=utf-8'});
fs.readFile(filePath2,(err,data)=>{
res.end(data);
})
}
})