您的当前位置:首页正文

文件夹列表

来源:图艺博知识网

准备

主流程嵌入

fs.stat() 中判断当前url映射为路径:

else if(!error && stats && stats.isDirectory && stats.isDirectory() ){
    require('./lib/directory').execute(pathname, root, req, resp);
}

directory 模块

  • 先创建一个html模板文件在 lib/tmpl/folder.html, 内容:
<!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') );
  • 获取文件夹列表并渲染结果, 如果获取失败输出异常的json格式数据
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,    //标题显示
            parent: pathname.match(/[\\\/]$/) ? "../" : "./",   //根据结尾分隔符处理回到上级目录链接
            base: "/"+pathname.replace(/(\w+)$/,"$1/")  //拼接目录链接和文件(夹)的绝对路径
        }) );
    }
});

PS:

Top