1.服务器渲染
A.第一步,导入模块库和第三方库
npm init
npm --registry https://registry.npmmirror.com install art-template moment
B.第二步,调整html文件
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><title>仿服务器资源</title></head><body><div class="container" style="width: 600px; margin: 0 auto"><h1>Index Of-2</h1><tableborder="1"width="600px"style="border-spacing: 0; text-align: center"><thead><th>图片</th><th>文件名称</th><th>最后更改时间</th><th>大小(字节)</th><th>文件类型</th></thead><tbody id="tShow">{{each data}}<tr>{{if $value.type == 'F'}}<td><img src="./imgs/file.png" width="50" alt="" /></td>{{else }}<td><img src="./imgs/folder.png" width="50" alt="" /></td>{{/if}}<td>{{$value.uname}}</td><td>{{$value.mtime}}</td><td>{{$value.size}}</td><td>{{$value.type=='F'?'文件':'文件夹'}}</td></tr>{{/each}}</tbody></table></div></body><script></script>
</html>
调整js文件
var http = require("http");
var fs = require("fs");
var moment = require("moment");
var template = require("art-template"); // 第三方模块,读取数据的
template.defaults.root = "./"; // 设置文件读取路径为相对路径!!!!var server = http.createServer();server.on("request", function (req, res) {// 防止乱码res.setHeader("Content-Type", "text/html;charset=utf-8");var ulrs = req.url;// 普通html文档if (req.url == "/") {fs.readdir("./", "utf8", function (err, data) {console.log(data, "datadir");var data_arr = []; // 返回的结果var count = 0; // 计数for (var i = 0; i < data.length; i++) {data_arr[i] = {};// 异步,闭包(function (i) {fs.stat(data[i], function (err1, data1) {// 数量叠加count++;// 判断是否为文件if (data1.isFile()) {data_arr[i].type = "F";} else {data_arr[i].type = "NF";}data_arr[i].uname = data[i];// 为了读取时间更友好,采用第三方模块data_arr[i].mtime = moment(data1.mtime).format("YYYY-MM-DD HH:mm:ss");data_arr[i].size = data1.size;// 跳出闭包,并返回值if (count == data.length) {res.end(template("./01index.html", { data: data_arr }));}});})(i);}});} else {// 其他资源fs.readFile("." + ulrs, function (err, data) {res.end(data);});}
});// 端口
server.listen(5657, function () {console.log("端口5657已启动,正在加载......");
});
效果图: