【问题标题】:MeteorJS realtime feedback from server streamMeteorJS 来自服务器流的实时反馈
【发布时间】:2016-01-06 20:49:06
【问题描述】:

我正在编写一个 Meteor 应用程序,它在服务器上执行多个 shell 命令。我想要从服务器到客户端的实时输出,但我无法弄清楚实时部分。我不想等待命令完成 - 因为它可能需要很长时间。

现在我已经创建了一个 Logs Mongo 集合来存储输出。但是我收到了这样的错误:“错误:Meteor 代码必须始终在 Fiber 中运行。尝试包装你传递给非 Meteor 库的回调Meteor.bindEnvironment。”

听起来我 Meteor 想让我等到所有输出都写完。我不想 wrapAsync 因为我希望在客户端逐行打印异步输出。 Spawn 在服务器上返回一个流,以便覆盖这一侧,我只是在流向客户端时遇到问题。这是一个例子:

Logs = new Mongo.Collection("logs");

if (Meteor.isClient) {

  Template.body.helpers({
    log: function(branchName) {
      return Logs.find({});
    }
  });

  Template.branch.events({
    'click button#start': function(event, template) {
      Meteor.call('startStack', template.data, function(error, result) {
        if(error){
          console.log(error);
        } else {
          console.log('response: ', result);
        }
      });
    }
  });

}

if (Meteor.isServer) {
  spawn = Npm.require('child_process').spawn;

  Meteor.methods({

    startStack: function(branch) {
      command = spawn('sh', ['-c', "ls && sleep 2 && ls -l && sleep 3 && ls -la"]);

      Logs.update({ branch: branch['name'] }, { branch: branch['name'], text:''}, { upsert : true });

      command.stdout.on('data', function (data) {
        // TODO: concat to existing text
        Logs.update({ branch: branch['name'] },  { branch: branch['name'], text: ''+data}); 
      });
    }
  });

}

【问题讨论】:

    标签: mongodb meteor


    【解决方案1】:

    Meteor.bindEnvironment() 应该可以解决您的问题:

    command.stdout.on('data', 
        Meteor.bindEnvironment(
            function (data) {
                Logs.update({ branch: branch['name'] },  { branch: branch['name'], text: ''+data}); 
            }
        )
    );
    

    如果要在服务器端的回调中执行 Meteor.update(),则需要在回调函数中使用 wrapAsync 或 Meteor.bindEnvironment()。当我需要使用第三方库(如 Stripe)然后需要根据服务器端的回调更新一些数据时,这是我使用的。

    【讨论】:

    • 谢谢。看起来这正是我所需要的。以为这很简单。仍然在流星模型周围环绕我的头。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-24
    • 1970-01-01
    相关资源
    最近更新 更多