Created
April 7, 2022 05:43
-
-
Save mayankchoubey/04c5521469c5ae823e1ab6103ba1505f 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 = "./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