Skip to content

Instantly share code, notes, and snippets.

@aimuz
Forked from mayankchoubey/deno_static_file_server.ts
Last active February 11, 2023 08:42
Show Gist options
  • Save aimuz/1283c90e0599d2bb089297f1fbd4c8d1 to your computer and use it in GitHub Desktop.
Save aimuz/1283c90e0599d2bb089297f1fbd4c8d1 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 = "";
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: 80 });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment