node-file-router icon indicating copy to clipboard operation
node-file-router copied to clipboard

How to handle serving of static files

Open EskelCz opened this issue 1 year ago • 2 comments

Hi, I love this project. One thing I can't figure out though is how to (in addition to javascript routes) also serve image files. The router doesn't seem to recognize them. Maybe I'm doing something wrong but I can't find anything in the documentation about it. Is this supported? Thanks.

For reference I'm using this basic setup:

import https from 'https'
import { initFileRouter } from 'node-file-router'

const useFileRouter = await initFileRouter({
  baseDir: 'src/routes'
})

async function handleRequest (req, res) {
  await useFileRouter(req, res)
}

https.createServer(options, handleRequest).listen(env.PORT)

EskelCz avatar Aug 31 '24 22:08 EskelCz

@EskelCz Hi, thank you!

Static files are not part of the current functionality yet. However, I might have an idea of how it's possible to use them :) I'll figure out a solution and get back to you this week.

Danilqa avatar Sep 01 '24 14:09 Danilqa

@Danilqa Thanks :) Meanwhile I have solved it like this:

async function serveStaticFile (req, res) {
  const safeSuffix = path.normalize(req.url).replace(/^(\.\.[\/\\])+/, '')
  const filePath = path.join('public', safeSuffix)
  try {
    const stat = await fs.stat(filePath)
    if (stat.isFile()) {
      const contentType = mime.lookup(filePath) || 'application/octet-stream'
      res.setHeader('Content-Type', contentType)
      const fileStream = await fs.readFile(filePath)
      res.end(fileStream)
      return true
    }
  } catch (err) {
    if (err.code !== 'ENOENT') {
      console.error(`Error serving static file: ${err}`)
      res.statusCode = 500
      res.end('Internal Server Error')
      return true
    }
  }
  return false
}

async function handleRequest (req, res) {
    const isStaticFile = await serveStaticFile(req, res)
    if (!isStaticFile) {
      await useFileRouter(req, res)
    }
}

It's not pretty but it seems to work fine for now.

EskelCz avatar Sep 01 '24 23:09 EskelCz