1

How can I call a Python function with my Node.js (express) backend server?

I want to call this function and give it an image url

def predictImage(img_path):
    # load model
    model = load_model("model.h5")
    # load a single image
    new_image = load_image(img_path)

    # check prediction
    pred = model.predict(new_image)

    return str(pred)
bruno desthuilliers
  • 75,974
  • 6
  • 88
  • 118
  • you can run python command using child_process and can call the required function. This link may be useful https://www.geeksforgeeks.org/run-python-script-node-js-using-child-process-spawn-method/ – LMSharma Mar 12 '19 at 13:59
  • The fact it's a python script is totally irrelevant, the question would be exactly the same if it was a shell script or any executable binary. – bruno desthuilliers Mar 13 '19 at 13:01

1 Answers1

1

You can put this function in separated file; let's called it 'test.py' for example.

In the Js file:

const { exec } = require('child_process');

function runPythonScript(){
    return new Promise((resolve, reject) => {
        exec('python test.py', (err, stdout, stderr) => {
            if(err) reject(err);

            resolve(stdout);
        });
    });
}

and call the function runPythonScript in express route.

runPythonScript()
.then(result => res.send(result))
Nimer Awad
  • 3,967
  • 3
  • 17
  • 31