1 回答
TA贡献1796条经验 获得超4个赞
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);
})
}
- 1 回答
- 0 关注
- 57 浏览
添加回答
举报