1.代码var http = require("http");var path = require("path");var url = require("url");var fs = require("fs");var ejs = require("ejs");var server = http.createServer(function (req, res) { if (req.url == "/favicon.ico") { return; } var pathname = url.parse(req.url).pathname; var fileUrl = path.normalize("./public/" + pathname); var extname = path.extname(pathname); fs.readFile(fileUrl, function (err, fileData) { getMime(extname, function (mime) { res.writeHead(200, { "context-type": mime }); res.end(fileData); }) }); if (pathname == "/") { var _thisUrl = "./public" var fileArry = [];//存储各个文件data的一些数据 var a = {} var data = {};//存储file(是否事文件,1是,0不是);fileName:文件(夹)名;url:文件实际地址 fs.readdir(_thisUrl, function (err, files) { var length = files.length; (function iterator(i) { var show = 0; if (i >= files.length) { data = { "fa": fileArry, "length": length }; fs.readFile("./views/index.ejs", function (err, fileData) { var template = fileData.toString(); var html = ejs.render(template, data); console.log(html); res.end(html); }); return; } fs.stat(_thisUrl + "/" + files[i], function (err, stats) { if (stats.isDirectory()) { a = { "file": 0, "fileName": files[i], "url": _thisUrl + "/" + files[i] } } else { if (path.extname("/" + files[i]).toLocaleLowerCase() == ".jpg") { show = 1; } a = { "file": 1, "fileName": files[i], "url": _thisUrl + "/" + files[i], "show": show } } fileArry.push(a); //console.log(fileArry); iterator(i + 1); }) })(0); }); };});server.listen(3000, "127.0.0.1");function getMime(extname, fn) { fs.readFile("./public/mime.json", function (err, data) { var mimeList = JSON.parse(data); var mime = mimeList[extname]; fn(mime); })}2.控制台截图我是小白,请解释的稍微浅显些,谢谢各位大神。
慕的地8271018
相关分类