From 04477643ec403fa0cdd2db5fe3f13cd77bb4f506 Mon Sep 17 00:00:00 2001 From: Wu Han Date: Tue, 12 Jan 2021 12:17:37 +0000 Subject: [PATCH] [fix] readdir synchronously --- server.js | 92 ++++++++++++++++++++++++++----------------------------- 1 file changed, 44 insertions(+), 48 deletions(-) diff --git a/server.js b/server.js index 8951f07..4124953 100644 --- a/server.js +++ b/server.js @@ -115,63 +115,59 @@ var update_submission = (socket, sessionID) => { socket.emit('info', 'Got output') // Read output dir - fs.readdir(output_dir, (err, files) => { - if (err) { - console.log(err) - return - } + files = fs.readdirSync(output_dir) + // Read each result in txt file + files.forEach(file => { + if (path.extname(file) === '.txt') { + var i = 0 - // Read each result in txt file - files.forEach(file => { - if (path.extname(file) === '.txt') { - var i = 0 + // Result object + var obj = {} + obj.name = file - // Result object - var obj = {} - obj.name = file + try { + // read contents of the file + const data = fs.readFileSync(output_dir + file, 'UTF-8') - try { - // read contents of the file - const data = fs.readFileSync(output_dir + file, 'UTF-8') + // split the contents by new line + const lines = data.split(/\r?\n/) - // split the contents by new line - const lines = data.split(/\r?\n/) - - lines.forEach((line) => { - i = i + 1 - // The first line is the fitness - if(i == 1) { - var fitness = parseFloat(line) - if(fitness < 0) { - obj.fitness = parseInt(line) - } - else { - obj.fitness = fitness - } + lines.forEach((line) => { + i = i + 1 + // The first line is the fitness + if(i == 1) { + var fitness = parseFloat(line) + if(fitness < 0) { + obj.fitness = parseInt(line) } - // The second line is the path - else if (i == 2) { - // Only read when there is no error - if(obj.fitness > 0) { - solution_array = line.split(",") - for(var j = 0; j < solution_array.length; j++) { - solution_array[i] = parseInt(solution_array[i], 10) - } - obj.solution = solution_array - } - else { - obj.solution = [] - } + else { + obj.fitness = fitness } - }) - } catch (err) { - console.error(err) - } - res.push(obj) + } + // The second line is the path + else if (i == 2) { + // Only read when there is no error + if(obj.fitness > 0) { + solution_array = line.split(",") + for(var j = 0; j < solution_array.length; j++) { + solution_array[i] = parseInt(solution_array[i], 10) + } + obj.solution = solution_array + } + else { + obj.solution = [] + } + } + }) + } catch (err) { + console.error(err) } - }) + console.log(obj) + res.push(obj) + } }) if (res.length === 0) { + console.log(res) socket.emit('error', 'Please check my_model.py') } socket.emit('result', JSON.stringify(res))