Priyansh Blog
Python + JavaScript = 🔥🔥🔥
Priyansh Sharma

Priyansh Sharma

08-06-2022

Python + JavaScript = 🔥🔥🔥

So what if we could build our backend mostly using NodeJS and only use Python when we have to.

That would be awesome right? We can use 

child process

in Node.JS to run a python script when needed.

const spawn = require('child_process').spawn
app.get("process_data", (req, res) => 
{spawn('python3', ['script.py'])})

And if we want we can pass data to our python script also.

const spawn = require('child_process').spawnapp.get("process_data", (req, res) => {const msg = "Hello"spawn('python3', ['script.py', msg])})

In Python in order to be able to read the data you must import the sys module.

import sys, jsondef main():msg = sys.argv[1]doSometing(msg)
if __name__ == '__main__':main()

Now instead on passing data while spawning the Python process, lets send data in stream.

const spawn = require('child_process').spawn,
const py = spawn('python3', ['script.py'])
const data = {msg: "Hello"}py.stdin.write(JSON.stringify(data)) //we have to send data as a string, so we are using JSON.stringifypy.stdin.end()

Finally we can send response back to our nodejs from the python script

const spawn = require('child_process').spawnconst py = spawn('python3', ['cscript.py'])py.stdout.on('data', function(res){let data = JSON.parse(res.toString())console.log(data)})
import sys# You will have your own implementation of get data. In this case lets assume it returns a dict/json
res = getData()print(json.dumps(data))sys.stdout.flush()

Priyansh Sharma

Priyansh Sharma

Founder of DocChat, DoTok & Pinzeal

Post your comment

Related Posts

Categories