Spawning child process with express endpoint

Viewed 68

I am trying to run my python program using express server and child processes. The method works fine if it is written just in plain NodeJS, but it is not working when i try to add it on my express API endpoint. Any suggestions please ?

// calling python script
app.get("/api", (req, res) => {
  let largeDataSet = [];
  // spawn new child process to call the python script
  const python = spawn("python", ["./mic/main.py"]);

  // collecting data from script
  python.stdout.on("data", function (data) {
    console.log(`${data}`);
    largeDataSet.push(data);
    console.log(`${largeDataSet}`);
  });
  python.stderr.on("data", (data) => {
    console.log(`stderr ${data}`);
  });
  python.on("close", (code) => {
    console.log(`child process close all stdio with code ${code}`);
    // send data to browser
    res.send(largeDataSet.join(""));
  });
});
1 Answers
function readLargeFile() {
    return new Promise((resolve, reject) => {
        let largeDataSet = [];
        // spawn new child process to call the python script
        const python = spawn("python", ["./mic/main.py"]);

        // collecting data from script
        python.stdout.on("data", function (data) {
            console.log(`${data}`);
            largeDataSet.push(data);
            console.log(`${largeDataSet}`);
        });
        python.stderr.on("data", (data) => {
            console.log(`stderr ${data}`);
            reject()
        });
        python.on("close", (code) => {
            console.log(`child process close all stdio with code ${code}`);
            // send data to browser
            resolve(largeDataSet.join(""));
        });
    })
}

app.get("/api", async (req, res) => {
    try {
        const result = await readLargeFile();
        res.send(result);
    } catch (err) {
        console.log(err);
        res.send(err);
    }

});
Related