繁体   English   中英

Meteor同步执行系统命令

[英]Meteor execute system command synchronously

我用c ++构建了一个简单的模型,我希望meteor与之交互。 目前,该模型作为命令行运行,一切运行良好,但调用命令行是异步完成的。 该模型非常快,因此我不需要结果进行回调,而且在此过程中涉及回调使得流星的数据库访问更加复杂,这是我想要避免的。

所以,我们只是进入常规问题:如何在javascript中制作异步同步...

我知道这已经使用节点进行了讨论,这个主题已在这里得到解答: node.js同步执行系统命令

这就是说,如何在流星内实际/设置这个?

我们应该使用npm安装软件包,但是当Meteor改变它的分发系统时,它是什么让它自己处理npm软件包? 看看这里 ,看看我说的是,我一直没能找到有关这个package.js任何相关信息

为了避免安装外部软件包,我考虑使用由meteor内部使用的Fibers ,但仍然:有人有一个关于如何用它封装异步调用的例子吗? 最后但并非最不重要的是,Fibers开发人员几乎建议我们不要直接使用Fiber进行编码,而是使用其他已经使用过的子工具...为什么不呢,但我回到了关于如何包含npm包的问题

我的代码看起来像这样(有点简化):

function callToEngine(argument, callback)
            {
               var result = null;
               var modelPath = "/some/where"

               var require = Npm.require;
               var spawn = require('child_process').spawn;
               var model = spawn(modelPath, []);
               var answerBuffer = "";

               engine.stdin.write(argument);
               engine.stdin.end(); //flush

                engine.stdout.on('data', function(data)
                {
                    answerBuffer+=data;
                });

                engine.stderr.on('data', function(data)
                {
                    console.log('stderr: ' + data);
                });

                engine.on('close', function(code)
                {
                    result = JSON.parse(answerBuffer);
                    console.log('child process exited with code ' + code);
                    callback(result);
                });
            }

我希望有类似的东西:

var result = callToEngine(argument);

你可以使用未来:

function callToEngine(argument) {
    var Future = Npm.require('fibers/future');

    var fut = new Future();


    ///do stuff

    engine.on('close', function(code)
            {
                result = JSON.parse(answerBuffer);
                console.log('child process exited with code ' + code);
                fut.return(result);
            });

    return fut.wait();
}

然后简单地使用:

var result = callToEngine(argument);

未来将确保返回只会在fut.return运行时返回一些东西

有关Meteor异步指南中其他设计的更多信息: https//gist.github.com/possibilities/3443021

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM