How to call a function in Python using Node.js

Welcome, in this blog we are going to learn how to call a function in Python script using Node.js. It is one of the most popular server-side frameworks. Node.js is a framework of javascript programming language. Websites use Node.js as a backend framework while developing their website. But unfortunately, it doesn’t support machine learning and artificial intelligence libraries. So Integrating python with Node.js is an important technique as many developers who create applications in python want to deploy those applications on online webpages, hence this is a nice way to do it. This application is used in machine learning and also it helps us to take advantage of some features that are exclusive to a particular programming language.

Program: call a function in Python using Node.js

Below is a python script to add two numbers. We have to import the sys library in python program to integrate it with node.js
sys.stdout.flush() is a method to send data to node.js. The arguments sys.argv[1] and sys.argv[2] are the data that python gets from node.js.

Python Code-

import sys

def sum(firstVar,secondVar):
    return firstVar + secondVar


Below is the server-side code of Node.js

Node.js Code-

var app   = require("express")();
var spawn = require("child_process").spawn;

app.get("\sum",function(req, res){
    var pyPro = spawn("python",["./",[1],[2]]);

    if(err) throw err;
    console.log("Server Started");

child_process is a package of node.js which allows us to use the spawn method for importing python functions.

When a user clicks a link that gets him transferred to “\sum”, the Node.js server interacts with the python script and produces the sum of the two numbers which are taken from the server.

Also read: How to create a Node.js Server

Thank you.

Leave a Reply

Your email address will not be published. Required fields are marked *