-
-
Notifications
You must be signed in to change notification settings - Fork 624
/
serve-static.ts
45 lines (41 loc) · 1.11 KB
/
serve-static.ts
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
import type { ServeStaticOptions } from '../../middleware/serve-static'
import { serveStatic as baseServeStatic } from '../../middleware/serve-static'
import type { Env, MiddlewareHandler } from '../../types'
const { open, lstatSync, errors } = Deno
export const serveStatic = <E extends Env = Env>(
options: ServeStaticOptions<E>
): MiddlewareHandler => {
return async function serveStatic(c, next) {
const getContent = async (path: string) => {
try {
if (isDir(path)) {
return null
}
const file = await open(path)
return file.readable
} catch (e) {
if (!(e instanceof errors.NotFound)) {
console.warn(`${e}`)
}
return null
}
}
const pathResolve = (path: string) => {
return path.startsWith('/') ? path : `./${path}`
}
const isDir = (path: string) => {
let isDir
try {
const stat = lstatSync(path)
isDir = stat.isDirectory
} catch {}
return isDir
}
return baseServeStatic({
...options,
getContent,
pathResolve,
isDir,
})(c, next)
}
}