#static file server with Deno.readFile(Sync)

3 messages · Page 1 of 1 (latest)

dark elk
#

i'm trying to make a webserver that serves a folder of static file, but it has to be using Deno.readFile (or readFileSync), because i'm also trying to bundle the webserver directory with the binary, and the library i'm using to create the fake filesystem (https://deno.land/x/leaf@v1.0.4) only supports that method of accessing files.

here's what i have so far:

export const handleStatic = async (requestEvent: Deno.RequestEvent) => {
    const BASE_PATH = '../frontend/dist'
    const pathName = new URL(requestEvent.request.url).pathname
    const filePath = BASE_PATH + (pathName === '/' ? '/index.html' : pathName)
    let fileSize;

    console.log(filePath)

  try {
    fileSize = (await Deno.stat(filePath)).size;
  } catch (e) {
    if (e instanceof Deno.errors.NotFound) {
      await requestEvent.respondWith(new Response(null, { status: 404 }))
            return
    }
    await requestEvent.respondWith(new Response(null, { status: 500 }))
            return
  }

  const body = (await Deno.open(filePath)).readable;
  await requestEvent.respondWith(new Response(body, {
    headers: {
      'content-length': fileSize.toString(),
      'content-type': contentType(extname(filePath)) || 'application/octet-stream',
    }
  }))
}
summer jetty
#

have you tied the std/fileserver?

"https://deno.land/std@0.177.0/http/file_server.ts"
#
import { serve } from "https://deno.land/std@0.177.0/http/server.ts"
import { join } from "https://deno.land/std@0.177.0/path/mod.ts";
import { serveFile } from "https://deno.land/std@0.177.0/http/file_server.ts"

// Start the server -> routes all requests to the handler below
serve(handleRequest)

// Handle all HTTP requests
function handleRequest(request: Request): Promise<Response> {
   // Get and adjust the requested path name
   let { pathname } = new URL(request.url); // get the path name
   if (pathname === '/') pathname = '/index.html'; // fix root
   // find the file -> get the content -> return it in a response
   return serveFile(request, join(Deno.cwd() + pathname));
}