Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

ChatGPT helped me replicate a code hosting service for esm.sh's playground. #823

Unanswered
boomyao asked this question in Show and tell
Discussion options

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);
You must be logged in to vote

Replies: 0 comments

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
1 participant

AltStyle によって変換されたページ (->オリジナル) /