Integrating Python with the MERN Stack

So, you started to develop your MERN Stack application, and just then you have a task to integrate a machine learning model or a python script with your application. You don’t have time to switch your whole application to use flask now 😕. Well guess what? You can connect you python script to your Node JS backend in a matter of minutes.

Below I have given you simple steps on how you can connect python with Node JS. In this step by step approach, I will be utilising the child_process standard library in Node JS to spawn a python process.

Before, we go into the steps, let us go through a bit about the child_process module.

“ The child_process module provides the ability to spawn subprocesses in a manner that is similar, but not identical, to popen(3). This capability is primarily provided by the child_process.spawn() function ”

For more details, you can go through the API documentation provided by Node JS: https://nodejs.org/api/child_process.html

Step 01

In your Node JS implementation file, import the child_process module, like shown below:

var spawn = require('child_process').spawn;

Step 02

Next step spawn a process and define the python file (script.py) you want to run, along with the data you want to pass to it (text)

const process = spawn('python', ['script.py', text]);

Note: You can pass in as many arguments as you want to the python script.

Step 03

process.stdout.on('data', (data) => {
test = data.toString();
});

Here we are saying that every time our node application receives data from the python process output stream, we want to convert that data which was received into a string and append it to the overall test variable.

Step 04

Incase you encounter any errors in the python script, the below code will console log it on to the terminal.

process.stderr.on('data', (data) => {
console.log('err results: %j', data.toString('utf8'))
});

Step 05

The final step is to simply log the data, if needed once the stream is done using on ‘end’

process.stdout.on('end', function(){
console.log('Test Data', test);
});

Finally your code will be as shown below:

var spawn = require('child_process').spawn;
const process = spawn('python', ['script.py', text]);
process.stdout.on('data', (data) => {
test = data.toString();
});
process.stderr.on('data', (data) => {
console.log('err results: %j', data.toString('utf8'))
});
process.stdout.on('end', function(){
console.log('Test Data', test);
});

That is all that’s there to it 🙌. With just a few simple steps as shown above you will be able to connect your python scripts with node js.

Author: Dilmi Kottachchi