如何同步使用node exec?
How to use node exec synchronously?
我有一种情况需要同步执行exec。怎么办呢?我找到了一个 lib execSync。但它是贬值的。所以任何其他解决方案。我可以为此使用 bluebird promise 吗?
for (var i = 0; i < testCasesLength; i++) {
var currentTestCase = testCases[i];
output.testCases.push({ passed: false, name: currentTestCase.name, input: currentTestCase.name, output: null });
fs.writeFileSync(path + "/input" + i + ".txt", currentTestCase.input);
var command = "cd " + path + " & java Main < input" + i + ".txt";
exec(command, function(error, stdout, stderr) {
if (error) {
if (exports.stats) {
console.log('INFO: '.green + path + '/Main.java contained an error while executing');
}
if (error.toString().indexOf('Error: stdout maxBuffer exceeded.') != -1) {
output.error = 'Error: stdout maxBuffer exceeded. You might have initialized an infinite loop.';
fn(output);
} else {
output.error = stderr;
fn(output);
}
} else {
if (exports.stats) {
console.log('INFO: '.green + path + '/Main.java successfully compiled and executed !');
}
// On success test Running
if (stdout == currentTestCase.output) {
output.testCases[i].passed = true;
output.score = output.score + parseInt(currentTestCase.score);
} else {
output.testCases[i].output = stdout;
}
}
});
}
fn(output);
我建议使用 async module with eachSeries 函数来同步获取它
async.eachSeries(testCasesLength,function(item,callback){
//return callback after exec command completed, the next iteration will not execute until get callback()
});
我有一种情况需要同步执行exec。怎么办呢?我找到了一个 lib execSync。但它是贬值的。所以任何其他解决方案。我可以为此使用 bluebird promise 吗?
for (var i = 0; i < testCasesLength; i++) {
var currentTestCase = testCases[i];
output.testCases.push({ passed: false, name: currentTestCase.name, input: currentTestCase.name, output: null });
fs.writeFileSync(path + "/input" + i + ".txt", currentTestCase.input);
var command = "cd " + path + " & java Main < input" + i + ".txt";
exec(command, function(error, stdout, stderr) {
if (error) {
if (exports.stats) {
console.log('INFO: '.green + path + '/Main.java contained an error while executing');
}
if (error.toString().indexOf('Error: stdout maxBuffer exceeded.') != -1) {
output.error = 'Error: stdout maxBuffer exceeded. You might have initialized an infinite loop.';
fn(output);
} else {
output.error = stderr;
fn(output);
}
} else {
if (exports.stats) {
console.log('INFO: '.green + path + '/Main.java successfully compiled and executed !');
}
// On success test Running
if (stdout == currentTestCase.output) {
output.testCases[i].passed = true;
output.score = output.score + parseInt(currentTestCase.score);
} else {
output.testCases[i].output = stdout;
}
}
});
}
fn(output);
我建议使用 async module with eachSeries 函数来同步获取它
async.eachSeries(testCasesLength,function(item,callback){
//return callback after exec command completed, the next iteration will not execute until get callback()
});