Node.js和Jake - 如何在任务中同步调用系统命令?

时间:2011-07-20 00:50:13

标签: javascript node.js jake

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
});

2 个答案:

答案 0 :(得分:2)

我通过重新阅读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
});

答案 1 :(得分:1)

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

示例:

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

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