generating and serving static files with Meteor

后端 未结 4 1585
温柔的废话
温柔的废话 2020-12-02 16:23

I\'m looking to create static text files based upon the content of a supplied object, which can then be downloaded by the user. Here\'s what I was planning on doing:

4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-02 16:46

    In version 0.6.6.3 0.7.x - 1.3.x you can do the following:

    To write

    var fs = Npm.require('fs');
    var filePath = process.env.PWD + '/.uploads_dir_on_server/' + fileName;
    fs.writeFileSync(filePath, data, 'binary');
    

    To serve

    In vanilla meteor app

    var fs = Npm.require('fs');
    WebApp.connectHandlers.use(function(req, res, next) {
        var re = /^\/uploads_url_prefix\/(.*)$/.exec(req.url);
        if (re !== null) {   // Only handle URLs that start with /uploads_url_prefix/*
            var filePath = process.env.PWD + '/.uploads_dir_on_server/' + re[1];
            var data = fs.readFileSync(filePath);
            res.writeHead(200, {
                    'Content-Type': 'image'
                });
            res.write(data);
            res.end();
        } else {  // Other urls will have default behaviors
            next();
        }
    });
    

    When using iron:router

    This should be a server side route (ex: defined in a file in /server/ folder)

    Edit (2016-May-9)

    var fs = Npm.require('fs');
    Router.route('uploads', {
           name: 'uploads',
           path: /^\/uploads_url_prefix\/(.*)$/,
           where: 'server',
           action: function() {
               var filePath = process.env.PWD + '/.uploads_dir_on_server/' + this.params[0];
               var data = fs.readFileSync(filePath);
               this.response.writeHead(200, {
                   'Content-Type': 'image'
               });
               this.response.write(data);
               this.response.end();
           }
        });
    

    Outdated format:

    Router.map(function() {
        this.route('serverFile', {
            ...// same as object above
        }
    });
    

    Notes

    • process.env.PWD will give you the project root
    • if you plan to put files inside your project

      • don't use the public or private meteor folders
      • use dot folders (eg. hidden folders ex: .uploads)

      Not respecting these two will cause local meteor to restart on every upload, unless you run your meteor app with: meteor run --production

    • I've used this approach for a simple image upload & serve (based on dario's version)
    • Should you wish for more complex file management please consider CollectionFS

提交回复
热议问题