0

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> }
EDGAR MEDINA
  • 111
  • 1
  • 9
  • 1
    Have you tried `pyprog.on('close',...)` or `pyprog.on('exit',...)` ? Docs here https://nodejs.org/api/child_process.html#child_process_class_childprocess – Molda Nov 25 '20 at 09:29

1 Answers1

0

I agree with @Molda. I assume stdout.on("end") is for EOF in this context. If it is emitted at all . process.stdout is a net.Socket so Socket.on('end') is the closest applicable info that I found. Which does imply the same assumption I am making within a net context. I could not find anything more specific.