expressjs / serve-static

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

add prefixing functionality #92

Closed fooloomanzoo closed 7 years ago

fooloomanzoo commented 7 years ago

Adding support for a prefix function in options to dynamically prefixing the paths. This could be usefull to serve different subfolders statically depeneding on the user-agent or other parts of the request. For example:

var express = require('express')
var serveStatic = require('serve-static')

var app = express()

app.use(serveStatic('/build', {
  prefix: serveByUserAgent
})

app.listen(3000)

function serveByUserAgent(req) {
  var userAgent = req.get('user-agent');
  // test user-agent for 'Internet Explorer'
  if (userAgent.match(/(MSIE)/i)) {
    return '/compiled'
  }
  return '/bundled'
}
dougwilson commented 7 years ago

Why not just use Express directly? You can then alter any option based on any input, which is more flexible than the solution in this PR.

var express = require('express')
var serveStatic = require('serve-static')

var app = express()

app.use(ifUserAgent(/(MSIE)/i, serveStatic('/compiled/build')))
app.use(ifNotUserAgent(/(MSIE)/i, serveStatic('/bundled/build')))

app.listen(3000)

function ifNotUserAgent (regex, middleware) {
  return function (req, res, next) {
    if (regex.test(req.get('user-agent'))) return next()
    return middleware(req, res, next)
  }
}

function ifUserAgent (regex, middleware) {
  return function (req, res, next) {
    if (!regex.test(req.get('user-agent'))) return next()
    return middleware(req, res, next)
  }
}

I'm sure you can simplify that wrapper even further and even publish as a Node.js module to allow folks to alter any middleware based on user agent.

fooloomanzoo commented 7 years ago

You are totally right. I wasn't so forward thinking, in the express way. You could include this example in the README.md because it seams like a very good example for a middleware