I'm looking to find out if it's possible to serve only one type of file (filtered by extension) out of an Express.js static directory.
For example, let's say I have the following Static directory:
Static
FileOne.js
FileTwo.less
FileThree.html
FileFour.js
And say I want to make only files with a .js
extension available to any given request, and all other requests would get a 500 response (or something like that).
How would I go about achieving this? Does Express have a baked-in filter that I haven't been able to find, or do I need to use regular expressions?
I use
app.get(/static\/.*js$/, function(r, s){
or
app.get('*', function(r, s){
if(r.url.match(/.*js$/)) // then serve
})
Doesn't appear to me that you can configure the "static" middleware in this way. In the "serve-static" module, which is the replacement for "static" for Express 4.0 (currently in RC stage), there are some options, but not filtering.
If you want just to serve *.js files, you can create a route yourself. Create an app.get('/static/*')
that responds with the file content and proper mime type, if the requested file is .js.
An alternative is to fork the "static" module, or better the new "serve-static", so it fits your needs. For example, you could create a new library copying the contents of this file, and after the line
var originalUrl = url.parse(req.originalUrl);
You may add something like
if(originalUrl.slice(-3) != '.js') return next();
This should ignore (calling the next middleware) all requests for static files that aren't ending in ".js". (untested, but it's inspired by the code above)
With the code above, create a new library (e.g. save it in "lib/my-static.js") and include it:
app.use(require('lib/my-static'))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With