generated from ButterDebugger/deno-jsr-template
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.ts
More file actions
45 lines (39 loc) · 1.42 KB
/
server.ts
File metadata and controls
45 lines (39 loc) · 1.42 KB
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
export default {
fetch: async (req: Request) => {
const url = new URL(req.url);
const pathname = decodeURIComponent(url.pathname);
try {
// Serve files from dist folder
if (pathname.startsWith("/dist/")) {
const filepath = `${Deno.cwd()}/dist/${pathname.substring(6)}`;
const file = await Deno.open(filepath, {
read: true,
});
return new Response(file.readable, {
headers: createHeaders(filepath),
});
}
// Serve static files
const filepath = pathname.endsWith("/")
? `${Deno.cwd()}/public/${pathname}/index.html`
: `${Deno.cwd()}/public/${pathname}`;
const file = await Deno.open(filepath, {
read: true,
});
return new Response(file.readable, {
headers: createHeaders(filepath),
});
} catch {
return new Response("404 Not Found", { status: 404 });
}
},
} satisfies Deno.ServeDefaultExport;
function createHeaders(filepath: string): Headers {
if (filepath.endsWith(".js")) {
return new Headers({ "content-type": "text/javascript" });
}
if (filepath.endsWith(".js.map")) {
return new Headers({ "content-type": "application/json" });
}
return new Headers();
}