在ExpressJS中基于文件扩展的中间件执行

有什么标准的方式将文件扩展名映射到Express中的特定中间件适配器?

当在生产中发生以".map"结尾的文件扩展名的请求时,我想显式返回一个404,但是在开发过程中,文件将被提供/允许(如果存在)。

此外,我注意到,如果"map"文件( 源映射文件 )不存在,即使文件不存在(这是低效的),会话提供者仍然为该请求激活。 所以,这也有助于防止不必要的会话加载/保存。

在安装session中间件之前,我已经添加了这个代码:

 app.use(function(req, res, next) { if (req && req.originalUrl) { var originalUrl = url.parse(req.originalUrl); var testMap = /^.*\.map$/; if (testMap.test(originalUrl.pathname)) { console.log("[MAP] %s %s", req.method, req.url); res.send(404); res.end(); return; } else { next(); } } }); 

虽然它的作品:

 [MAP] GET /javascripts/vendor/jquery.min.map 

我想我可以使用第一个参数来指定文件path(特别是扩展名)? 但是,我似乎无法得到正确的语法(我尝试了上面使用的正则expression式,但它似乎并没有工作)。

编辑(以下是从我的app.js文件块上面的行):

 // all environments app.set('port', process.env.PORT || 4000); app.set('views', path.join(process.cwd(), 'views')); app.set('view engine', 'dust'); app.engine('dust', dustjs.dust({ layout: 'main_layout', cache: false })); app.use(express.favicon()); app.use(express.logger('dev')); app.use(express.methodOverride()); app.use(express.cookieParser(cookieSecret)); // I've tried to move this before and after the "map" code, to no effect app.use(express.static(path.join(__dirname, 'public'))); 

这应该工作;

 app.use('*.map', function (req, res, next) { // disable requests ending in .map in production if ('production' === app.get('env')) { console.log("[MAP] %s %s", req.method, req.url); res.send(404); } else { next(); } });