最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Serve only .js files from an Express static directory? - Stack Overflow

programmeradmin4浏览0评论

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'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?

Share Improve this question asked Mar 13, 2014 at 23:29 AJBAJB 7,60015 gold badges60 silver badges91 bronze badges 0
Add a ment  | 

2 Answers 2

Reset to default 6

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'))
发布评论

评论列表(0)

  1. 暂无评论