Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to handle serving of static files #61

Open
EskelCz opened this issue Aug 31, 2024 · 2 comments
Open

How to handle serving of static files #61

EskelCz opened this issue Aug 31, 2024 · 2 comments

Comments

@EskelCz
Copy link

EskelCz commented Aug 31, 2024

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)
@Danilqa
Copy link
Owner

Danilqa commented Sep 1, 2024

@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.

@EskelCz
Copy link
Author

EskelCz commented Sep 1, 2024

@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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants