-
-
Notifications
You must be signed in to change notification settings - Fork 192
ChatGPT helped me replicate a code hosting service for esm.sh's playground. #823
Unanswered
boomyao
asked this question in
Show and tell
-
import { join, extname } from "https://deno.land/std/path/mod.ts";
import { exists } from "https://deno.land/std/fs/mod.ts";
import { transpile } from "https://deno.land/x/emit/mod.ts";
async function handleRequest(request: Request): Promise<Response> {
const url = new URL(request.url);
let path = url.pathname;
// Serve index.html by default
if (path === "/") {
path = "/index.html";
}
const filePath = join("public", path);
const fileExists = await exists(filePath);
if (!fileExists) {
return new Response("File not found", { status: 404 });
}
const ext = extname(filePath);
if (ext === ".ts" || ext === ".tsx") {
// Read TypeScript file
// const source = await Deno.readTextFile(filePath);
// Compile TypeScript to JavaScript
const url = new URL(filePath, import.meta.url);
const result = await transpile(filePath);
const code = result.get(url.href)
return new Response(code, {
headers: { "content-type": "application/javascript" },
});
}
// Serve other files directly
const contentType = getContentType(ext) || "application/octet-stream";
const content = await Deno.readFile(filePath);
return new Response(content, { headers: { "content-type": contentType } });
}
function getContentType(ext: string): string | undefined {
const types: { [key: string]: string } = {
".html": "text/html",
".js": "text/javascript",
".css": "text/css",
".png": "image/png",
".jpg": "image/jpeg",
};
return types[ext];
}
Deno.serve(handleRequest);
Beta Was this translation helpful? Give feedback.
All reactions
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment