簡體   English   中英

如何使用node.js執行多個Shell命令?

[英]How to execute multiple shell commands using node.js?

也許我還沒有開始理解異步范例,但是我想做這樣的事情:

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命令時,總是嵌套這些回調似乎有點奇怪。 沒有更好的方法嗎?

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

異步提供了許多其他選擇。 閱讀文檔並嘗試一下! 請注意,對於f3_length我在調用exec時僅使用了callback 您也可以與其他調用一起執行此操作(因此您的代碼會更短)。 我只是想向您展示它是如何工作的。

在以下情況下,我個人使用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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM