How to Communicate between Node.js and Python
In this article, we will see how to, send data from node.js to python script and get the result back.
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
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
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 is 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, python script sends the data in buffer form i.e <Buffer 7b 22 73 75 ......>
This buffer is converted to a string via toString
method.
Hope this article helps!
Searching for Jobs?
Tracking Job Applications can be tough since they are spread across multiple platforms. Griffin provides a dashboard that keeps a track of all your Job Applications in a single place. It is now available for download on Google Play Store!