-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdev-server.js
More file actions
44 lines (33 loc) · 1.17 KB
/
dev-server.js
File metadata and controls
44 lines (33 loc) · 1.17 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
import { extname, resolve } from 'node:path';
const port = Number(process.env.PORT || 3000);
const rootDir = resolve(import.meta.dir, 'src');
function resolvePath(pathname) {
const relativePath = pathname === '/' ? 'index.html' : pathname.slice(1);
const targetPath = resolve(rootDir, relativePath);
if (targetPath !== rootDir && !targetPath.startsWith(`${rootDir}/`)) {
return null;
}
return targetPath;
}
const server = Bun.serve({
port,
development: true,
async fetch(req) {
const url = new URL(req.url);
const pathname = decodeURIComponent(url.pathname);
const targetPath = resolvePath(pathname);
if (!targetPath) {
return new Response('Not found', { status: 404 });
}
const file = Bun.file(targetPath);
if (await file.exists()) {
return new Response(file);
}
if (!extname(pathname)) {
const fallback = Bun.file(resolve(rootDir, 'index.html'));
return new Response(fallback);
}
return new Response('Not found', { status: 404 });
}
});
console.log(`Dev server running at http://localhost:${server.port}`);