【问题标题】:Node.js and Jake - How to call system commands synchronously within a task?Node.js 和 Jake - 如何在任务中同步调用系统命令?
【发布时间】:2013-02-06 07:23:47
【问题描述】:

Jake 任务执行一个长时间运行的系统命令。另一个任务取决于第一个任务在开始之前完全完成。 'child_process' 的 'exec' 函数异步执行系统命令,使得第二个任务可以在第一个任务完成之前开始。

编写 Jakefile 以确保第一个任务中长时间运行的系统命令在第二个任务开始之前完成的最干净的方法是什么?

我曾考虑在第一个任务结束时在虚拟循环中使用轮询,但这闻起来很糟糕。似乎必须有更好的方法。我见过this SO question,但它并没有完全解决我的问题。

var exec = require('child_process').exec;

desc('first task');
task('first', [], function(params) {
  exec('long running system command');
});

desc('second task');
task('second', ['first'], function(params) {
  // do something dependent on the completion of 'first' task
});

【问题讨论】:

    标签: javascript node.js jake


    【解决方案1】:

    通过重新阅读Matthew Eernisse's post,我找到了自己问题的答案。对于那些想知道如何做到这一点的人:

    var exec = require('child_process').exec;
    
    desc('first task');
    task('first', [], function(params) {
      exec('long running system command', function() {
        complete();
      });
    }, true); // this prevents task from exiting until complete() is called
    
    desc('second task');
    task('second', ['first'], function(params) {
      // do something dependent on the completion of 'first' task
    });
    

    【讨论】:

    • 为什么不让第一个任务在完成后发出一个信号,而该信号的侦听器产生第二个任务?
    【解决方案2】:

    仅供参考,我有一个没有其他依赖项的同步 exec 模块。

    例子:

    var allsync = require("allsync");
    allsync.exec( "find /", function(data){
        process.stdout.write(data);
    });
    console.log("Done!");
    

    在上面的示例中,Done 仅在存在find 进程之后打印exec 函数基本上会阻塞,直到完成。

    【讨论】:

      猜你喜欢
      • 2011-05-25
      • 2015-08-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-22
      • 1970-01-01
      • 2010-12-17
      • 1970-01-01
      相关资源
      最近更新 更多