gpt4 book ai didi

javascript - 如何同步使用node exec?

转载 作者:行者123 更新时间:2023-12-03 05:48:02 26 4
gpt4 key购买 nike

我有一种情况,我需要同步执行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模块 eachSeries函数以同步方式获取它

async.eachSeries(testCasesLength,function(item,callback){
//return callback after exec command completed, the next iteration will not execute until get callback()
});

关于javascript - 如何同步使用node exec?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40256440/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com