简体   繁体   中英

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?

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 (eg save it in "lib/my-static.js") and include it:

app.use(require('lib/my-static'))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM