相關推薦:《nodejs 教學》
#在建立HTTP 伺服器實作了一個最簡單的靜態資源伺服器,可以對程式碼進行寫改造,增加資料夾預覽功能,暴露出一些配置,變成一個可自訂的靜態資源伺服器模組
可自訂的靜態資源伺服器理想的使用方式應該是這樣的
1 2 3 4 5 6 7 8 9 10 |
|
這樣的使用方式就要求程式碼實作模組化,Node.js 實作一個模組非常簡單
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 49 50 51 52 53 54 |
|
完整程式碼:https://github.com/Samaritan89/ static-server/tree/v1
執行npm run test
可以測試
1 2 3 4 5 6 7 8 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
|
遍歷產生html 部分需要用到資料夾操作章節介紹的知識,為了方便產生HTML,demo 使用了Handlebar 範本引擎,主要邏輯透過git 程式碼修改記錄可以清楚看到本次的變更:https://github.com/Samaritan89/static-server/commit/5565788dc317f29372f6e67e6fd55ec92323d0ea##npm run test
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
if
(stats.isDirectory()) {
// 如果是文件夹则遍历文件夹,生成改文件夹内的文件树
const
dir = fs.opendirSync(filePath);
let dirent = dir.readSync();
while
(dirent) {
list.push({
name: dirent.name,
path: path.join(url, dirent.name),
type: dirent.isDirectory() ?
'folder'
:
'file'
,
});
dirent = dir.readSync();
}
dir.close();
res.writeHead(200, {
'content-type'
:
'text/html'
,
});
// 对文件顺序重排,文件夹在文件前面,相同类型按字母排序,不区分大小写
list.sort((x, y) => {
if
(x.type > y.type) {
// 'folder' > 'file', 返回 -1,folder 在 file 之前
return
-1;
}
else
if
(x.type == y.type) {
return
compare(x.name.toLowerCase(), y.name.toLowerCase());
}
else
{
return
1;
}
});
// 使用 handlebars 模板引擎,生成目录页面 html
const
html = template({ list });
res.
end
(html);
}
登入後複製
,使用瀏覽器存取127.0.0.1:9527
可以看到目錄檔案的展示##完整程式碼:https://github. com/Samaritan89/static-server/tree/v2
更多程式相關知識,請造訪:
程式設計教學
以上是Node.js學習之靜態資源伺服器的詳細內容。更多資訊請關注PHP中文網其他相關文章!