利用node核心模块http结合art-template构建Apache读取文件目录的效果

http构建类似Apache读取目录

  • 主要代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
const fs = require('fs');
const http = require('http');
const template = require('art-template');
const path = require('path');

//测试目录
const testDir = 'd:/NodeTest/www';

let server = http.createServer();
server.on('request', function (req, res) {
let url = req.url;
// 1. 如果是文件,直接读取响应
// 2. 如果是目录,读取渲染目录列表
// 3. 如果目录并且有该目录中有 index.html 则直接渲染目录中的 index.html

//path.join()使用平台特定的分隔符把所有 path 片段连接到一起,并规范化生成的路径。
// 空字符串的 path 片段会被忽略。 如果连接后的路径是一个空字符串,则返回 '.',表示当前工作目录。
let urlPath = path.join(testDir, url);
//fs.stat()查看文件的属性。如果要检查文件是否存在但不操作它,建议使用 fs.access()。
fs.stat(urlPath, function (err, stats) {
if (err) {
return res.end('404 Not Find')
} else {
if (stats.isFile()) { //是否是文件
fs.readFile(urlPath, function (err, data) {
if (err) {
return res.end('404 Not Find')
} else {
res.end(data)
}
})
} else if (stats.isDirectory()) { //是否是文件夹
//fs.readFileSync() 返回文件的内容。如果指定了 encoding,则返回字符串,否则返回 buffer。
let tplStr = fs.readFileSync('./static-template.html').toString();
//fs.readdirSync(path[, options])读取目录内容
let files = fs.readdirSync(urlPath);

let html = template.render(tplStr, {files: files});
res.end(html);
}
}
})

});

server.listen(3000, function () {
console.log('server is running ...');
});