Home > front end >  Node Child Process (Spawn) is not returning data correctly when using with function
Node Child Process (Spawn) is not returning data correctly when using with function

Time:10-25

I am trying to generate a new score based on the output of my python script. The python script returning the data correctly and JS program printing correctly but the problem is when i return the value and print it, it shows undefined

Function Code -

async function generateCanadaScore(creditscore = 0) {
  console.log(creditscore, "creditscore"); //prints 300
  let MexicoData = 0;
  const python = spawn("python", [
    "cp_production.py",
    "sample_dill.pkl",
    "mexico",
    Number(creditscore),
  ]);

  await python.stdout.on("data", function (data) {
    console.log("Pipe data from python script ...");
    console.log(data.toString()); //prints number 
    MexicoData = data.toString();
    console.log(MexicoData) // prints number
//working fine till here printing MexicoData Correctly (Output from py file) , problem in return
    return MexicoData ;
  });
  python.stderr.on("data", (data) => {
    console.log(data); // this function doesn't run
  });
// return MexicoData ; already tried by adding return statement here still same error
}

Calling Function Code -

app.listen(3005, async () => {
  console.log("server is started");
  //function calling 
  // Only for testing purpose in listen function 
  let data = await generateCanadaScore(300);
  console.log(data, "data"); // undefined
});

I will not be able to share python code it is confidential.

CodePudding user response:

You can't await on the event handler. (It returns undefined, so you're basically doing await Promise.resolve(undefined), which waits for nothing).

You might want to wrap your child process management using new Promise() (which you'll need since child_process is a callback-async API, and you need promise-async APIs):

const {spawn} = require("child_process");

function getChildProcessOutput(program, args = []) {
  return new Promise((resolve, reject) => {
    let buf = "";
    const child = spawn(program, args);

    child.stdout.on("data", (data) => {
      buf  = data;
    });

    child.on("close", (code) => {
      if (code !== 0) {
        return reject(`${program} died with ${code}`);
      }
      resolve(buf);
    });
  });
}

async function generateCanadaScore(creditscore = 0) {
  const output = await getChildProcessOutput("python", [
    "cp_production.py",
    "sample_dill.pkl",
    "mexico",
    Number(creditscore),
  ]);
  return output;
}

  • Related