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

后端 未结 2 1231
忘了有多久
忘了有多久 2021-01-15 06:32

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

2条回答
  •  Happy的楠姐
    2021-01-15 07:30

    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.

提交回复
热议问题