準(zhǔn)備
使用 $npm install http-f2e-server@0.0.6
進(jìn)行安裝之前版本,本篇在此基礎(chǔ)上開(kāi)發(fā)一個(gè)基于模板引擎的文件夾列表展示
主流程嵌入
從 fs.stat()
中判斷當(dāng)前url映射為路徑:
else if(!error && stats && stats.isDirectory && stats.isDirectory() ){
require('./lib/directory').execute(pathname, root, req, resp);
}
directory 模塊
- 先創(chuàng)建一個(gè)html模板文件在
lib/tmpl/folder.html
, 內(nèi)容:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title><%=title%></title>
</head>
<body>
<ul>
<li><a href="<%=parent%>">../</a></li>
<%files.forEach(function(file){
print( '<li><a href="'+base+file+'">'+file+'</a></li>' );
})%>
</ul>
</body>
</html>
- 加載該文件文本到模塊中:
var template = _.template( fs.readFileSync( __dirname + '/tmpl/folder.html','utf-8') );
- 獲取文件夾列表并渲染結(jié)果殉疼, 如果獲取失敗輸出異常的json格式數(shù)據(jù)
fs.readdir(root+pathname, function(error, files){
if(error){
resp.writeHead(500, {"Content-Type": mime.lookup( ".json" )});
resp.end( JSON.stringify( error ) )
}else{
resp.end( template({
files: files, //文件(夾)列表
title: pathname, //標(biāo)題顯示
parent: pathname.match(/[\\\/]$/) ? "../" : "./", //根據(jù)結(jié)尾分隔符處理回到上級(jí)目錄鏈接
base: "/"+pathname.replace(/(\w+)$/,"$1/") //拼接目錄鏈接和文件(夾)的絕對(duì)路徑
}) );
}
});
PS:
相關(guān)完整代碼已經(jīng)發(fā)布到了npm倉(cāng)庫(kù)中窄绒, 可以使用 $npm install http-f2e-server@0.0.7
進(jìn)行安裝或者更新呢堰。進(jìn)入目錄后使用 $node http-f2e-server.js
啟動(dòng)服務(wù)挚歧,并查看Demo。