How to Communicate between Node.js and Python
We will be creating a simple addition script in python and call it via node.js
First, create two files namely add.py and index.js
Now in index.js add the below code:
//We will have to create a childprocess in order tocall python script.
var spawn = require("child_process").spawn;
//This process is called here.
var process = spawn('python',["./add.py",7,3] );
//We listen for 'data' event.
process.stdout.on('data', function (data) {
console.log("Sum " + JSON.parse(data.toString()).sum);
});Now let’s go through the code, first we import spawn from the “child_process” module, which takes two arguments, first the command to run and second an array of arguments. the 0th index of the array is reserved for the filename. And the rest is the input passed to the child process.
We then listen for the ‘data’ event i.e wait for the child process to transmit the data.
Why did we use JSON here? 😕 Because we return the object from python in JSON format as its always easier to handle JSON. 😌
Why did we use data.toString()? You will have the answer to this question by the end of this article.
Now let’s complete add.py
import sys
import json
x = {
"sum": int(sys.argv[1]) + int(sys.argv[2])
}
print(json.dumps(x))
The inputs we passed in the child process are retrieved by sys.argv[1] and sys.argv[2]. Remember it was an array, hence the indexing.
json.dumps() creates a JSON object. The print() sends the data to the parent process i.e to javascript (in this case)
This data is then printed by the console.log() statement in javascript. The data in our case is simply the sum of two numbers.
Now coming back to the question, why did we use thetoString() method? Here is the answer, the python script sends the data in buffer form i.e This buffer is converted to a string via the toString method.
Hope this article helps!