Code coverage report for thinkjs/lib/Lib/Behavior/CheckResourceBehavior.js

Statements: 100% (21 / 21)      Branches: 100% (11 / 11)      Functions: 100% (2 / 2)      Lines: 100% (21 / 21)      Ignored: none     

All files » thinkjs/lib/Lib/Behavior/ » CheckResourceBehavior.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 412 2         2   2         10 1   9 9 5   9   9 5     4 4 4 3 3 3   1 1     4      
var fs = require('fs');
var mime = require('mime');
/**
 * 静态资源请求
 * @return {[type]} [description]
 */
module.exports = Behavior(function(){
  'use strict';
  return {
    options: {
      'url_resource_on': false
    },
    run: function(){
      if (!global.RESOURCE_PATH || !this.options.url_resource_on || !this.http.pathname) {
        return false;
      }
      var pathname = this.http.pathname;
      if (pathname.indexOf('/') === 0) {
        pathname = pathname.substr(1);
      }
      var reg = C('url_resource_reg');
      //通过正则判断是否是静态资源请求
      if (!reg.test(pathname)) {
        return false;
      }
 
      var file = RESOURCE_PATH + '/' + pathname;
      var res = this.http.res;
      if (fs.existsSync(file)) {
        var contentType = mime.lookup(file);
        res.setHeader('Content-Type', contentType + '; charset=' + C('encoding'));
        tag('resource_output', this.http, file);
      }else{
        res.statusCode = 404;
        res.end();
      }
      //返回一个pendding promise, 不让后续执行
      return getDefer().promise;
    }
  };
});