Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serve only .js files from an Express static directory?

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?

like image 723
AJB Avatar asked Oct 01 '22 07:10

AJB


2 Answers

I use

app.get(/static\/.*js$/, function(r, s){

or

app.get('*', function(r, s){
  if(r.url.match(/.*js$/)) // then serve
})
like image 74
John Williams Avatar answered Oct 08 '22 22:10

John Williams


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'))
like image 43
ItalyPaleAle Avatar answered Oct 08 '22 21:10

ItalyPaleAle