如何使用node.js执行多个shell命令?

4
也许我还没有掌握异步编程范式,但我想要做这样的事情:
var exec, start;
exec = require('child_process').exec;
start = function() {
  return exec("wc -l file1 | cut -f1 -d' '", function(error, f1_length) {
    return exec("wc -l file2 | cut -f1 -d' '", function(error, f2_length) {
      return exec("wc -l file3 | cut -f1 -d' '", function(error, f3_length) {
        return do_something_with(f1_length, f2_length, f3_length);
      });
    });
  });
};

每次想要添加新的shell命令时,嵌套这些回调似乎有点奇怪。有没有更好的方法来做到这一点呢?


2
异步JS来救援!https://github.com/caolan/async - freakish
2个回答

7
作为Xavi所说,你可以使用TwoStep。另一方面,我使用Async JS库。你的代码可能如下所示:
async.parallel([
    function(callback) {
        exec("wc -l file1 | cut -f1 -d' '", function(error, f1_length) {
            if (error)
                return callback(error);
            callback(null, f1_length);
        });
    },
    function(callback) {
        exec("wc -l file2 | cut -f1 -d' '", function(error, f2_length) {
            if (error)
                return callback(error);
            callback(null, f2_length);
        });
    },
    function(callback) {
        exec("wc -l file3 | cut -f1 -d' '", callback);
    }
],
function(error, results) {
    /* If there is no error, then
       results is an array [f1_length, f2_length, f3_length] */
    if (error)
        return console.log(error);
    do_something_with(results);
});

Async提供了很多其他的选项。阅读文档并尝试使用!请注意,对于f3_length,我在调用exec时只使用了callback。您也可以在其他调用中这样做(这样您的代码会更短)。我只是想向您展示它是如何工作的。

3

在这些情况下,我个人使用TwoStep

var TwoStep = require("two-step");
var exec, start;
exec = require('child_process').exec;
start = function() {
  TwoStep(
    function() {
      exec("wc -l file1 | cut -f1 -d' '", this.val("f1_length"));
      exec("wc -l file2 | cut -f1 -d' '", this.val("f2_length"));
      exec("wc -l file3 | cut -f1 -d' '", this.val("f3_length"));
    },
    function(err, f1_length, f2_length, f3_length) {
      do_something_with(f1_length, f2_length, f3_length);
    }
  );
};

虽然如此,市面上有许多流程控制库可供选择。我鼓励你尝试一些:https://github.com/joyent/node/wiki/Modules#wiki-async-flow


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接