Performance: Serving static files
Serving static files impacts the page load speed by affecting how quickly resources like images, CSS, and JavaScript are delivered to the browser.
import { serveFile } from "https://deno.land/std/http/file_server.ts"; import { serve } from "https://deno.land/std/http/server.ts"; serve(async (req) => { const url = new URL(req.url); if (url.pathname.startsWith('/static/')) { try { return await serveFile(req, `./public${url.pathname.replace('/static', '')}`); } catch { return new Response('Not Found', { status: 404 }); } } return new Response('Hello World'); });
import { serve } from "https://deno.land/std/http/server.ts"; serve(async (req) => { const url = new URL(req.url); if (url.pathname.startsWith('/static/')) { const filePath = `./public${url.pathname.replace('/static', '')}`; try { const file = await Deno.readFile(filePath); return new Response(file, { headers: { 'content-type': 'application/octet-stream' } }); } catch { return new Response('Not Found', { status: 404 }); } } return new Response('Hello World'); });
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Reading files on every request without caching | N/A | N/A | High due to delayed resource load | [X] Bad |
| Using serveFile with caching and streaming | N/A | N/A | Low due to fast resource delivery | [OK] Good |
/image.png?
import { serve } from "https://deno.land/std/http/server.ts";
import { serveFile } from "https://deno.land/std/http/file_server.ts";
serve(async (req) => {
const url = new URL(req.url);
if (url.pathname === "/image.png") {
return await serveFile(req, "./static/image.png");
}
return new Response("Not Found", { status: 404 });
});import { serve } from "https://deno.land/std/http/server.ts";
import { serveFile } from "https://deno.land/std/http/file_server.ts";
serve(async (req) => {
const url = new URL(req.url);
if (url.pathname = "/style.css") {
return await serveFile(req, "./static/style.css");
}
return new Response("Not Found", { status: 404 });
});public in Deno. Which approach correctly serves any requested file from that folder, falling back to a 404 if the file doesn't exist?
import { serve } from "https://deno.land/std/http/server.ts";
import { serveFile } from "https://deno.land/std/http/file_server.ts";
serve(async (req) => {
const url = new URL(req.url);
try {
// Which line correctly serves the file?
return await ???;
} catch {
return new Response("Not Found", { status: 404 });
}
});Pass the test and this pattern moves unknown