How to make two programs, NodeJS, and Python, communicate?

Viewed 65

I have two programs. A server in NodeJS and a script in Python.

Basically, the script scrapes and writes data to a JSON file.

What I want to do, is to make the NodeJS server reset the JSON file without altering with the Python program.

I tried a simple writeFile, but it outputs random characters sometimes.

I know how to use signals, but I don't know if it's a good idea to interrupt my Python script randomly with a signal.

I also know how to use pipes, but is it a good idea ?

What can I do ?

1 Answers

You can use python-shell to be able to call python scripts in NodeJS, and wrap that script call inside a Promise to wait for the script to end, and after it ends overwrite or clean the JSON file from NodeJS. In this way you'll be 100% sure that the python script is not running when NodeJS does the cleansing of the JSON file.

const promise = await new Promise((resolve, reject) => {
  PythonShell.run(
    `/SCRIPT_PATH.py`,
    {
        args: [''], // ARRAY OF ARGUMENTS TO THE PYTHON SCRIPT
    },
    function (err, result) {
      if (err) reject({ success: false, message: err });
      resolve({ success: true, message: result });
    }
  );
});
if (promise.success) {
  // REST OF YOUR CODE IF THE SCRIPTS EXECUTES SUCCESSFULLY
}

P.S.: The result variable is the output of your script and you are able to pass parameters to the python script if it's needed in the args array.

Related