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

Node.js and Jake - How to call system commands synchronously within a task?

本文关键字:任务 同步 调用 系统命令 js Jake Node      更新时间:2023-09-26

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

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

我想过在第一个任务结束时在一个虚拟循环中使用轮询,但这听起来很糟糕。看来一定有更好的办法。我看到过这个SO问题,但它并没有完全解决我的问题。

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

通过重读Matthew Eernisse的帖子,我找到了自己问题的答案。对于那些想知道怎么做的人:

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

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

  • https://npmjs.org/package/allsync

的例子:

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

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