expressjs / serve-static

Serve static files
MIT License
1.38k stars 227 forks source link

feature request: enable mapping url to a different file via a callback #140

Closed sfmohassel closed 2 years ago

sfmohassel commented 3 years ago

There are situations when I need to map the request url (pathname & query) to a different file. For example when I want to modify a file, store the modified file someplace else then send it to client.

For this to work we would need a callback in middleware options to return the file path on disk:

getFilePath: (request: ExpressRequest) => string

This is useful specially when working on a middleware that would compress and/or resize images on the fly using pathname and query string.

dougwilson commented 2 years ago

Hi @saeidjoker thanks for the feature request. This is already possible in Express using res.sendFile (which is the exact same serving mechanism as this one). This module is just res.sendFile where it does the file resolution -- if you want to override the file resolution, there is no need to even use this module, as you just use res.sendFile. Here is an example:

app.use((req, res, next) => {
  const path = getFilePath(req)
  res.sendFile(path)
})

If this doesn't work for your use-case, please let us know what specifically this is not doing based on what you requested and we can re-open and/or fix res.sendFile to do what is missing.