denoland / deploy_feedback

For reporting issues with Deno Deploy
https://deno.com/deploy
74 stars 5 forks source link

[Bug]: Example Code Error For File Server Hosting #712

Open KaiMckiernan opened 2 months ago

KaiMckiernan commented 2 months ago

Problem description

I was trying to run a file server using deno and used this website for help: https://docs.deno.com/runtime/tutorials/file_server/#:~:text=The%20Deno%20standard%20library%20provides,%2Fbin%2Ffile%2Dserver%20.

The example(file_server.ts) uses does not run properly and error: Uncaught SyntaxError: Unexpected reserved word const file = await Deno.open("." + filepath, { read: true }); is logged in terminal

Steps to reproduce

  1. Go onto https://docs.deno.com/runtime/tutorials/file_server/#:~:text=The%20Deno%20standard%20library%20provides,%2Fbin%2Ffile%2Dserver%20.
  2. Copy and paste the example code from file_server.ts

    { hostname: "localhost", port: 8080 },
    (request) => {
    // Use the request pathname as filepath
    const url = new URL(request.url);
    const filepath = decodeURIComponent(url.pathname);
    
    // Try opening the file
    try {
      const file = await Deno.open("." + filepath, { read: true });
    
      // Stream the file as it's read to the response. That way we don't
      // need to load the full file into memory.
      return new Response(file.readable);
    } catch {
      // If the file cannot be opened, return a "404 Not Found" response
      return new Response("404 Not Found", { status: 404 });
    }
    },
    );
  3. Use deno run --allow-read=. --allow-net file_server.ts in terminal

Expected behavior

It should run and I should be able to open a browser on localhost

Environment

-Deno Version: 1.44.1 -OS: Edition: Windows 11 Home Version: 23H2 Installed on: ‎2023-‎03-‎31 OS build: 22631.4169 Experience: Windows Feature Experience Pack 1000.22700.1034.0

Possible solution

replace code with

Deno.serve(
  { hostname: "localhost", port: 8080 },
  async (request) => {
    // Use the request pathname as filepath
    const url = new URL(request.url);
    const filepath = decodeURIComponent(url.pathname);

    // Try opening the file
    try {
      const file = await Deno.open("." + filepath, { read: true });

      // Stream the file as it's read to the response. That way we don't
      // need to load the full file into memory.
      return new Response(file.readable);
    } catch {
      // If the file cannot be opened, return a "404 Not Found" response
      return new Response("404 Not Found", { status: 404 });
    }
  },
);

Additional context

No response