koa-static是一個(gè)koa-send的封裝,所以重點(diǎn)其實(shí)是koa-send.
koa-send會(huì)接收三個(gè)參數(shù),ctx,path與opt.
其中path是訪問(wèn)的url.opt.root是我們?cè)O(shè)置的靜態(tài)資源根路徑,他會(huì)被賦值給root.
path和root會(huì)被path的join和normalize拼接成一個(gè)規(guī)范化的路徑并賦值給path.這個(gè)path用來(lái)查找要傳輸?shù)奈募?
stats = await fs.stat(path)
如果他是一個(gè)目錄,那么就在那個(gè)目錄下查找是否有index.html文件.
if (stats.isDirectory()) {
if (format && index) {
// index為opt.index->index.html
path += '/' + index
stats = await fs.stat(path)
} else {
return
}
}
之后會(huì)用該path來(lái)創(chuàng)建一個(gè)可讀流,用于向客戶端傳遞數(shù)據(jù).
ctx.body = fs.createReadStream(path)
整個(gè)send模塊就是這樣了,koa-static的功能也是由它實(shí)現(xiàn)的.