2016-10-26 4 views
0

Ich habe eine Situation, in der ich exec synchron ausführen muss. Wie kann es gehen? Ich habe einen lib execSync gefunden. Aber es ist abgeschrieben. Also jede andere Lösung dafür. Kann ich das Bluebird-Versprechen dafür verwenden?Wie Knoten Exec synchron verwenden?

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); 

Antwort

1

Ich empfehle async Modul mit eachSeries Funktion zu verwenden, um es in syncronous Natur zu erhalten

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