Forked from mayankchoubey/deno_static_file_server.ts
Last active
February 11, 2023 08:42
-
-
Save aimuz/1283c90e0599d2bb089297f1fbd4c8d1 to your computer and use it in GitHub Desktop.
Deno static file server
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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