I'm building an API-Rest with Node.js and need to execute a python script that will generate a .json file and save it in a directory. Therefore I want to wait for the python program's termination so that node can use the output JSON file. This is the code that I implemented from How to call a Python function from Node.js
const { spawn } = require('child_process');
const pythonDir = (__dirname + "./"); // Path of python script folder
const python = pythonDir + "./env/Scripts/python"; // Path of the Python interpreter
function cleanWarning(error) {
return error.replace(/Detector is not able to detect the language reliably.\n/g,"");
}
function callPython(scriptName, args) {
return new Promise(function(success, reject) {
const script = pythonDir + scriptName;
const pyArgs = [script, JSON.stringify(args) ]
const pyprog = spawn(python, pyArgs );
let resultError = "";
pyprog.stderr.on('data', (data) => {
resultError += cleanWarning(data.toString());
});
pyprog.stdout.on("end", function(){
if(resultError == "") {
var result = require('./optimalRoute.json')
success(result);
}else{
console.error(`Python error, you can reproduce the error with: \n${python} ${script} ${pyArgs.join(" ")}`);
const error = new Error(resultError);
console.error(error);
reject(resultError);
}
})
});
}
module.exports.callPython = callPython;
Calling the function:
...
route: async function(req, res){
const pythonCaller = require("../models/routeGeneration");
const locaciones = require("../models/example");
const result = await pythonCaller.callPython("CVRP.py", {"delivery":locations});
}
...
think this is not working due to I got pending state forever, could someone help me?. Thanks
Promise { <pending> }