[英]How to execute multiple shell commands using node.js?
Maybe I haven't groked the asynchronous paradigm yet, but I want to do something like this: 也许我还没有开始理解异步范例,但是我想做这样的事情:
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);
});
});
});
};
It seems a little weird to keep nesting those callbacks every time I want to add a new shell command. 每当我想添加一个新的shell命令时,总是嵌套这些回调似乎有点奇怪。 Isn't there a better way to do it? 没有更好的方法吗?
As Xavi said you can use TwoStep. 正如Xavi所说的,您可以使用TwoStep。 On the other hand I use Async JS library. 另一方面,我使用Async JS库。 Your code may look like this: 您的代码可能如下所示:
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 gives tons of other options. 异步提供了许多其他选择。 Read the documentation and try it out! 阅读文档并尝试一下! Note that for f3_length
I just used callback
when calling exec
. 请注意,对于f3_length
我在调用exec
时仅使用了callback
。 You can do this with other calls as well (so your code will be shorter). 您也可以与其他调用一起执行此操作(因此您的代码会更短)。 I just wanted to show you how it works. 我只是想向您展示它是如何工作的。
I personally use TwoStep in these situations: 在以下情况下,我个人使用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);
}
);
};
That said, there are a ton of flow controll libraries out there. 也就是说,那里有大量的流控制库。 I encourage you to try some out: https://github.com/joyent/node/wiki/Modules#wiki-async-flow 我鼓励您尝试一下: https : //github.com/joyent/node/wiki/Modules#wiki-async-flow
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.