【问题标题】:Meteor JS : Serve static files and persist query stringMeteor JS:提供静态文件和持久化查询字符串
【发布时间】:2015-07-12 09:46:23
【问题描述】:

假设一个用户请求,domain.com/cat.png?user=name 我想要的只是提供 cat.png 并将 {user: name} 记录到 mongo。

我知道我可以在/public/ 中托管文件,但我需要记录来自 URL 请求的查询字符串参数,这就是我使用 Iron Router 功能的原因。我很乐意以其他方式(没有 Iron 路由器)。

以下是我的代码改编自其他 Stack Overflow 响应。

//Added meteorhacks:npm

var fs = Meteor.npmRequire('fs');
var file = fs.readFileSync('/public/cat.png'); 


// Iron Router

Router.route('/', function() {
    // Return valid image.
   this.response.writeHead(200, {
      'Content-type': 'image/png',
      'Content-Disposition': "attachment; filename=" + this.params.path
});
   this.response.end();

  //Run other tasks related to this download action
   myOtherFunctions();

 //Serve the file
   fs.createReadStream(file).pipe(this.response);
 });

问题 1:我什至没有让 fs 找到任何文件。对于 public/cat.png 的例子,控制台抱怨:

“错误:ENOENT,没有这样的文件或目录'/public/cat.png'”

问题 2:如果文件确实存在于“public”中,Meteor 将覆盖 Iron Router 的路由,并且事件 myOtherFunctions() 将永远不会运行。

【问题讨论】:

  • 文件前面不需要 /public。只需执行“/cat.png”
  • 如您所建议的,'/cat.png' 仍然存在同样的问题。您无法重现该问题吗?

标签: meteor


【解决方案1】:

问题 1: 这是因为fs.readFileSync 需要public 目录的绝对路径。 类似/home/User/yourMeteorApp/public/ + yourFilename

问题 2 不是真正的问题

在服务器上试试这个:

PATH_FOR_YOUR_APP = "/home/User/ ..." //change it
Router.route('/:fileName', {where: 'server'})
  .get(function () {
    this.response.writeHead(200, {
        'Content-type': 'image/png',
        'Content-Disposition': "attachment; filename=" + this.params.fileName
    });

    myOtherFunctions(); //here you look at query params and store {user: name} to mongo

    fs.createReadStream(PATH_FOR_YOUR_APP+"/public/"+this.params.fileName).pipe(this.response);
  })

【讨论】:

  • 这个绝对路径要求是个问题。在生产环境中部署时会发生什么?还是与其他开发者合作?
  • 这个 hack 将用于获取流星的绝对路径,并删除符号链接:PATH_FOR_YOUR_APP = path.resolve('.', '../../../../.. /')
猜你喜欢
  • 2012-10-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-04
相关资源
最近更新 更多