Setting Up a Static File Server with Deno: Step-by-Step Guide
Creating a static file server with Deno using its standard library is a straightforward task, thanks to Deno's built-in support for handling HTTP requests and file operations. Below is a step-by-step guide on how to set up a basic static file server in Deno that serves HTML, CSS, and JavaScript files.
Step-by-Step Implementation
-
Create Project Structure
First, set up a directory structure for your static site. For example:
/static ├── index.html ├── styles.css └── script.jsThis directory will contain the HTML, CSS, and JavaScript files to be served.
-
Set Up the Server Script
Create a file named
server.tsin the root directory of your project:import { serve } from "https://deno.land/std@0.150.0/http/server.ts"; import { extname, join } from "https://deno.land/std@0.150.0/path/mod.ts"; import { contentType } from "https://deno.land/std@0.150.0/media_types/mod.ts"; const port = 8000; const baseDir = "./static"; const handler = async (req: Request): Promise<Response> => { const url = new URL(req.url); const filepath = join(baseDir, url.pathname); try { const file = await Deno.readFile(filepath); // Determine Content-Type based on file extension const ext = extname(filepath); const mimeType = contentType(ext) || "application/octet-stream"; return new Response(file, { status: 200, headers: { "content-type": mimeType, }, }); } catch (error) { if (error instanceof Deno.errors.NotFound) { return new Response("File not found", { status: 404 }); } return new Response("Internal server error", { status: 500 }); } }; console.log(`HTTP webserver running. Access it at: http://localhost:${port}/`); serve(handler, { port }); -
Running the Server
Run the server using the Deno command-line interface. You will need to grant network and read file permissions:
deno run --allow-net --allow-read server.tsThis command instructs Deno to run the
server.tsfile with permissions to access the network and read files from the file system. -
Access the Server
Open a web browser and navigate to
http://localhost:8000/. You should see yourindex.htmlfile loaded and styled withstyles.css, and any JavaScript interactions should function as expected fromscript.js.
Explanation
- Serve Files: The
servefunction is utilized to create an HTTP server that listens for incoming requests. - URL Handling: For each request, we extract the path from the URL and resolve it against the
staticdirectory. - Content-Type: The
contentTypefunction automatically determines the correct MIME type of files based on their extension, ensuring proper formatting in the browser. - Error Handling: The server responds with a 404 error if a file is not found, and a 500 error for any other internal server errors.
This setup will efficiently serve your static files, making it a simple yet powerful way to host static websites using Deno.