首页 文章

Meteor:尝试在/ public之外提供静态文件

提问于
浏览
2

TLDR;如何通过铁路由器提供静态文件?如果我在/ public中放置一个文件,它会绕过我在铁路由器中使用的所有钩子 .

长版:我需要将所有请求记录到图像文件中 . 特别是'd like to persist to Mongodb the querystring in every request such as ' a = 1&b = 2'来自http://domain.com/cat.png?a=1&b=2 .

我没有看到在Meteor中这样做的方法 . 但我可以使用诸如params.query之类的铁路由器钩子 . 除了/ public中的任何静态文件都由Meteor的处理程序提供服务,并绕过铁路由器 .

(我希望使用最新的apis . 这里有许多帖子,前流星1.0和预铁路)

2 回答

  • 1

    当然有可能 . 您可以完全访问HTTP请求的请求和响应对象,甚至可以连接任意连接中间件 .

    这是我使用后者的解决方案,从 /tmp 目录提供:

    var serveStatic = Meteor.npmRequire('serve-static');
    
    if (Meteor.isClient) {
    }
    
    if (Meteor.isServer) {
        var serve = serveStatic('/tmp');
        // NOTE: this has to be an absolute path, since the relative
        // project directories change upon bundling/production
    
        Router.onBeforeAction(serve, {where: 'server'});
    
        Router.route('/:file', function () {
            this.next();
        }, {where: 'server'});
    }
    

    要使这项工作,你还需要npm包:

    meteor add meteorhacks:npm
    

    并且您需要将serve-static添加到packages.json文件中:

    {
        "serve-static": "1.10.0"
    }
    

    之后, /x.xyz URL上将显示任何文件 /tmp/x.xyz .

  • 1

    您可以使用 fs 来服务任何文件:

    Router.route('/static/:filename', function (){
      var fs = Npm.require('fs'),
          path = '/tmp/' + this.params.filename; // make sure to validate input here
    
      // read the file
      var chunk = fs.createReadStream(path);
    
      // prepare HTTP headers
      var headers = {}, // add Content-type, Content-Lenght etc. if you need
          statusCode = 200; // everything is OK, also could be 404, 500 etc.
    
      // out content of the file to the output stream
      this.response.writeHead(statusCode, headers);
      chunk.pipe(this.response);
    });
    

相关问题