Run Python script from Node.js using child process spawn() method - GeeksforGeeks

19 Feb, 2019
Node.js is one of the most adopted web development technologies but it lacks support for machine learning, deep learning and artificial intelligence libraries. Luckily, Python supports all these and many more other features. Django Framework for Python can utilize this functionality of Python and can provide support for building new age web application using machine learning and Artificial Intelligence.
For those developers who are not familiar with Django Framework but use Node JS framework can also benefit from Python using child process module for Node JS.
Child Process module for Node JS provides functionality to run scripts or commands in languages other than JavaScript too (like Python). We can implement machine learning algorithms, deep learning algorithms and many features provided via Python library into Node JS application. Child Process allows us to run Python script in Node JS application and stream in/out data into/from Python script.
child_process.spawn(): This method helps us to spawn child process asynchronously.
 Let’s create a simple Python script that will take two command line arguments as a first name and last name then display them. Later we’ll run that script from Node JS application and display output in the browser window.
Python script :
import sys# Takes first name and last name via command # line arguments and then display themprint("Output from Python")print("First name: " + sys.argv[1])print("Last name: " + sys.argv[2])  # save the script as hello.py
Node JS server code :
// import express JS module into app// and creates its variable.var express = require('express');var app = express();  // Creates a server which runs on port 3000 and // can be accessed through localhost:3000app.listen(3000, function() {    console.log('server running on port 3000');} )  // Function callName() is executed whenever // url is of the form localhost:3000/nameapp.get('/name', callName);  function callName(req, res) {          // Use child_process.spawn method from     // child_process module and assign it    // to variable spawn    var spawn = require("child_process").spawn;          // Parameters passed in spawn -    // 1. type_of_script    // 2. list containing Path of the script    //    and arguments for the script           // E.g : http://localhost:3000/name?firstname=Mike&lastname=Will    // so, first name = Mike and last name = Will    var process = spawn('python',["./hello.py",                            req.query.firstname,                            req.query.lastname] );      // Takes stdout data from script which executed    // with arguments and send this data to res object    process.stdout.on('data', function(data) {        res.send(data.toString());    } )}  // save code as start.js
After saving the Python script and server script code, run the code from its source folder by following command :
 node start.js 
Access the application through link :
localhost:3000/name?firstname="Enter first name"&lastname="Enter last name"

For e g. : localhost:3000/name?firstname=Ram&lastname=Sharma
Output :
Applications :
This method can be used in alternative to REST-APIs.This method can help our web application take benefits from other languages special features which are currently not available in javascriptMachine learning modules can be implemented in Python and then utilize them in web app using this method.
This method can be used in alternative to REST-APIs.
This method can help our web application take benefits from other languages special features which are currently not available in javascript
Machine learning modules can be implemented in Python and then utilize them in web app using this method.
Reference :
https://nodejs.org/api/child_process.html
JavaScript-Misc
JavaScript
Python
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe