Last active
January 3, 2022 07:15
-
-
Save mayankchoubey/2c6a2a9c61ed4757e17fb3a77b88a52b to your computer and use it in GitHub Desktop.
Deno content server by reading files directly
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 { readableStreamFromReader as toStream } from "https://deno.land/std/streams/mod.ts"; | |
| import { serve } from "https://deno.land/std/http/mod.ts"; | |
| const BASE_PATH = "./testdata"; | |
| const reqHandler = async (req: Request) => { | |
| const p = new URL(req.url).pathname; | |
| const filePath = BASE_PATH + p; | |
| let len = 0; | |
| try { | |
| len = (await Deno.stat(filePath)).size; | |
| } catch (err) { | |
| return new Response(null, { status: 404 }); | |
| } | |
| return new Response(toStream(await Deno.open(filePath)), { | |
| headers: { | |
| "content-length": `${len}`, | |
| }, | |
| }); | |
| }; | |
| serve(reqHandler, { port: 8000 }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment