Meteor / Node writeFile崩溃服务器

时间:2013-07-16 10:53:46

标签: node.js meteor filesystems

我有以下代码:

Meteor.methods({
  saveFile: function(blob, name, path, encoding) {
    var path = cleanPath(path), fs = __meteor_bootstrap__.require('fs'),
      name = cleanName(name || 'file'), encoding = encoding || 'binary',
      chroot = Meteor.chroot || 'public';
    // Clean up the path. Remove any initial and final '/' -we prefix them-,
    // any sort of attempt to go to the parent directory '..' and any empty directories in
    // between '/////' - which may happen after removing '..'
    path = chroot + (path ? '/' + path + '/' : '/');

    // TODO Add file existance checks, etc...
    fs.writeFile(path + name, blob, encoding, function(err) {
      if (err) {
        throw (new Meteor.Error(500, 'Failed to save file.', err));
      } else {
        console.log('The file ' + name + ' (' + encoding + ') was saved to ' + path);
      }
    }); 

    function cleanPath(str) {
      if (str) {
        return str.replace(/\.\./g,'').replace(/\/+/g,'').
          replace(/^\/+/,'').replace(/\/+$/,'');
      }
    }
    function cleanName(str) {
      return str.replace(/\.\./g,'').replace(/\//g,'');
    }
  }
});

我从这个项目中拿走了 https://gist.github.com/dariocravero/3922137

代码工作正常,它会保存文件,但是它会重复几次调用,并且每次使用Windows版本0.5.4导致meteor重置。 F12控制台最终看起来像这样:enter image description here。每次503发生时,meteor控制台都会循环启动代码,并在saveFile函数中重复控制台日志。

此外,在目标目录中,图像缩略图一直显示,然后显示为已损坏,然后再次显示有效缩略图,就像fs多次写入一样。

以下是调用函数的代码:

"click .savePhoto":function(e, template){
    e.preventDefault();
     var MAX_WIDTH = 400;
    var MAX_HEIGHT = 300;
    var id = e.srcElement.id;
    var item = Session.get("employeeItem");
    var file = template.find('input[name='+id+']').files[0];
  // $(template).append("Loading...");
  var dataURL = '/.bgimages/'+file.name;
    Meteor.saveFile(file, file.name, "/.bgimages/", function(){
        if(id=="goodPhoto"){
            EmployeeCollection.update(item._id, { $set: { good_photo: dataURL }});
        }else{
            EmployeeCollection.update(item._id, { $set: { bad_photo: dataURL }});
        }
        // Update an image on the page with the data
        $(template.find('img.'+id)).delay(1000).attr('src', dataURL);
    });     



},

导致服务器重置的原因是什么?

1 个答案:

答案 0 :(得分:3)

我的猜测是,由于Meteor内置了“自动目录扫描以搜索文件更改”,为了实现应用程序自动重新启动到最新的代码库,您创建的文件实际上是导致服务器重置。

Meteor不会扫描以点开头的目录(所谓的“隐藏”目录),例如.git,因此您可以通过将文件的路径设置为您的.directory来使用此行为。自己的。

你应该考虑使用writeFileSync,因为Meteor方法打算同步运行(在节点光纤内部),这与异步调用的常规节点方式相反,在这段代码中它没什么大不了但是例如你不能使用任何Meteor writeFile回调中的机制。

asynchronousCall(function(error,result){
    if(error){
        // handle error
    }
    else{
        // do something with result
        Collection.update(id,result);// error ! Meteor code must run inside fiber
    }
});

var result=synchronousCall();
Collection.update(id,result);// good to go !

当然有一种方法可以使用光纤/未来在同步调用中转换任何异步调用,但这超出了这个问题的范围:我建议阅读此EventedMind episode on node future以了解这个特定区域。