-
Notifications
You must be signed in to change notification settings - Fork 98
Expand file tree
/
Copy pathserver.js
More file actions
79 lines (66 loc) · 2.32 KB
/
Copy pathserver.js
File metadata and controls
79 lines (66 loc) · 2.32 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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import "dotenv/config";
import http from "node:http";
import { readFileSync } from "node:fs";
import { fileURLToPath } from "node:url";
import { dirname, join } from "node:path";
import worker from "./index.js";
const PORT = Number(process.env.PORT) || 4000;
const BASE = process.env.BASE_PATH ?? "";
const __dir = dirname(fileURLToPath(import.meta.url));
const STATIC = {
"/": { file: "docs/landing.html", mime: "text/html" },
"/docs": { file: "docs/index.html", mime: "text/html" },
"/style.css": { file: "docs/style.css", mime: "text/css" },
"/logo.svg": { file: "docs/logo.svg", mime: "image/svg+xml" },
};
function serveStatic(res, entry) {
try {
const body = readFileSync(join(__dir, entry.file));
res.writeHead(200, {
"Content-Type": entry.mime + "; charset=utf-8",
"Cache-Control": "no-cache",
});
res.end(body);
} catch {
res.writeHead(404);
res.end("Not found");
}
}
async function nodeToRequest(req) {
const host = req.headers["host"] ?? `localhost:${PORT}`;
const stripped = BASE && req.url.startsWith(BASE) ? req.url.slice(BASE.length) || "/" : req.url;
const url = `http://${host}${stripped}`;
const chunks = [];
for await (const chunk of req) chunks.push(chunk);
const body = chunks.length ? Buffer.concat(chunks) : null;
return new Request(url, {
method: req.method,
headers: req.headers,
body: body?.length ? body : undefined,
duplex: "half",
});
}
const server = http.createServer(async (req, res) => {
console.log(`→ ${req.method} ${req.url}`);
const pathname = req.url.split("?")[0];
const staticEntry = STATIC[pathname];
if (req.method === "GET" && staticEntry) {
return serveStatic(res, staticEntry);
}
try {
const request = await nodeToRequest(req);
const response = await worker.fetch(request, {});
res.statusCode = response.status;
for (const [k, v] of response.headers) res.setHeader(k, v);
const buf = await response.arrayBuffer();
res.end(Buffer.from(buf));
} catch (err) {
console.error("Unhandled error:", err);
res.statusCode = 500;
res.setHeader("Content-Type", "application/json");
res.end(JSON.stringify({ error: err.message }));
}
});
server.listen(PORT, () => {
console.log(`Anivexa dev server → http://localhost:${PORT}`);
});