我的解決辦法是節點內的使用過程中spawn
,使用Promise
模式同步過程的執行,然後加入結果與Promise.all
(見功能promiseAll
這裏:
var promiseAll = function(items, block, done, fail) {
var self = this;
var promises = [],
index = 0;
items.forEach(function(item) {
promises.push(function(item, i) {
return new Promise(function(resolve, reject) {
if (block) {
block.apply(this, [item, index, resolve, reject]);
}
});
}(item, ++index))
});
Promise.all(promises).then(function AcceptHandler(results) {
if (done) done(results);
}, function ErrorHandler(error) {
if (fail) fail(error);
});
}; //promiseAll
現在做進口
var cp = require('child_process');
和寫入的執行塊將產生每個進程:
var ExecutionBlock = function(item, index, resolve, reject) {
var options = [
"--ssl-protocol", "tlsv1",
"--ignore-ssl-errors", "true"
];
options.push(executableFile); // push input file path
options.push(item); // push executable arguments
// LP: now spawn the power!
var child = spawn(settings.executable, options);
// Listen for an exit event:
child.on('exit', function(exitCode) {
console.log("Child exited with code: " + exitCode);
return resolve(exitCode);
});
// Listen for stdout data
child.stdout.on('data', function(data) {
console.log(data.toString());
});
// child error
child.stderr.on('data',
function(data) {
console.log('err data: ' + data);
// on error, kill this child
child.kill();
return reject(new Error(data.toString()));
}
);
} //ExecutionBlock
在這一點上,應該在inputItemsArray
有我們的可執行文件的參數列表中,我們可以通過Promise.All
方式運行它們:
// inputItemsArray is a list of arguments for the executable
promiseAll(inputItemsArray, function(item, index, resolve, reject) {
ExecutionBlock(item, index, resolve, reject);
}
,function(results) { // aggregated results
// all execution done here. The process exitCodes will be returned
// array index is the index of the processed that exited
}
,function(error) { // error
});
建成塊將匯聚一個數組中退出代碼,因爲我們已將它們退回resolve
。通過這種方式,您可以對執行過程進行良好的控制,在執行過程中爲每個進程分配exitCode
,最終爲stdout
和stderr
。
在要點here中的一個工作示例。