Skip to content

Instantly share code, notes, and snippets.

@mayankchoubey
Created April 7, 2022 05:43
Show Gist options
  • Save mayankchoubey/04c5521469c5ae823e1ab6103ba1505f to your computer and use it in GitHub Desktop.
Save mayankchoubey/04c5521469c5ae823e1ab6103ba1505f to your computer and use it in GitHub Desktop.
Deno static file server
import { serve } from "https://deno.land/std/http/mod.ts";
import { lookup } from "https://deno.land/x/media_types/mod.ts";
const BASE_PATH = "./public";
const reqHandler = async (req: Request) => {
const filePath = BASE_PATH + new URL(req.url).pathname;
let fileSize;
try {
fileSize = (await Deno.stat(filePath)).size;
} catch (e) {
if (e instanceof Deno.errors.NotFound) {
return new Response(null, { status: 404 });
}
return new Response(null, { status: 500 });
}
const body = (await Deno.open(filePath)).readable;
return new Response(body, {
headers: {
"content-length": fileSize.toString(),
"content-type": lookup(filePath) || "application/octet-stream",
},
});
};
serve(reqHandler, { port: 8080 });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment