Home

Setting Up a Static File Server with Deno: Step-by-Step Guide

447 views

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

  1. Create Project Structure

    First, set up a directory structure for your static site. For example:

    /static
      ├── index.html
      ├── styles.css
      └── script.js
    

    This directory will contain the HTML, CSS, and JavaScript files to be served.

  2. Set Up the Server Script

    Create a file named server.ts in 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 });
    
  3. 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.ts
    

    This command instructs Deno to run the server.ts file with permissions to access the network and read files from the file system.

  4. Access the Server

    Open a web browser and navigate to http://localhost:8000/. You should see your index.html file loaded and styled with styles.css, and any JavaScript interactions should function as expected from script.js.

Explanation

  • Serve Files: The serve function 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 static directory.
  • Content-Type: The contentType function 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.