Skip to content

Instantly share code, notes, and snippets.

@mayankchoubey
Last active January 3, 2022 07:15
Show Gist options
  • Save mayankchoubey/2c6a2a9c61ed4757e17fb3a77b88a52b to your computer and use it in GitHub Desktop.
Save mayankchoubey/2c6a2a9c61ed4757e17fb3a77b88a52b to your computer and use it in GitHub Desktop.
Deno content server by reading files directly
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