如何使用node.js执行多个shell命令?
也许我还没有探索过异步范例,但我想做如下事情:如何使用node.js执行多个shell命令?,node.js,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) {
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);
});
});
});
};
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);
});
每次我想添加一个新的shell命令时,总是嵌套这些回调似乎有点奇怪。难道没有更好的方法吗?我个人在这些情况下使用:
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);
}
);
};
也就是说,有大量的流量控制库。我鼓励您尝试一下:正如哈维所说,您可以使用TwoStep。另一方面,我使用图书馆。您的代码可能如下所示:
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);
});
});
});
};
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
。您也可以对其他调用执行此操作(因此您的代码将更短)。我只是想向您展示一下它是如何工作的。Async JS拯救一切!