Meteor: Trying to serve a static file outside of /public

女生的网名这么多〃 提交于 2019-12-19 10:08:39

问题


TLDR; How can one serve a static file through iron router? If I place a file in /public it bypasses all the hooks I could use in iron router.

Long version: I need to log all requests to an image file. Specifically I'd like to persist to Mongodb the querystring in every request such as 'a=1&b=2' from http://domain.com/cat.png?a=1&b=2.

I don't see a way of doing this in Meteor. But I could use the iron router hooks such as params.query . Except that any static files in /public get served by Meteor's handler, and bypasses iron router.

(I'm looking to use up to date apis. There are lots of posts here pre meteor 1.0 and pre ironrouter)


回答1:


Of course it is possible. You have full access to the request and response objects of the HTTP request, and you can even wire up arbitrary connect middleware.

Here is my solution using the latter, serving from the /tmp directory:

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'});
}

To make this work you'll also need the npm package:

meteor add meteorhacks:npm

And you'll need to add serve-static to your packages.json file:

{
    "serve-static": "1.10.0"
}

Afterwards, any file /tmp/x.xyz will be available on your /x.xyz URL.




回答2:


You can use fs to server any file:

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);
});


来源:https://stackoverflow.com/questions/31129209/meteor-trying-to-serve-a-static-file-outside-of-public

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!