kiran Gopal kiran Gopal - 1 month ago 10
Node.js Question

How to use node exec synchronously?

I have a situation where I need to execute exec synchronously. How can do it ? I found one lib execSync. But it is depreciated. So any other solution for this. Can I use bluebird promise for this ?

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

Answer

I recommend to use async module with eachSeries function to get it in syncronous nature

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