Python + JavaScript = πŸ”₯πŸ”₯πŸ”₯




When in involves Web Development nothing beats JavaScript. However typically we’ve got to do a bit extra demanding activity, for instance analyzing huge pile of knowledge. In that case Python is perhaps a superior possibility. However that is only one operate of our web site. Can we need to change to Python simply due to that one characteristic? Most likely not.



So what if we might construct our backend largely utilizing NodeJS and solely use Python when we’ve got to.

That might be superior proper? We are able to use little one course of in Node.JS to run a python script when wanted.

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

Exit fullscreen mode

# script.py
doSometing()
Enter fullscreen mode

Exit fullscreen mode

And if we wish we will cross knowledge to our python script additionally.

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

Exit fullscreen mode

In Python so as to have the ability to learn the information you should import the sys module.

import sys, json

def principal():
    msg = sys.argv[1]
    doSometing(msg)

if __name__ == '__main__':
    principal()
Enter fullscreen mode

Exit fullscreen mode

Now as an alternative on passing knowledge whereas spawning the Python course of, lets ship knowledge in stream.

const spawn = require('child_process').spawn,
const py = spawn('python3', ['script.py'])
const knowledge = {
    msg: "Whats up"
}

py.stdin.write(JSON.stringify(knowledge)) //we've got to ship knowledge as a string, so we're utilizing JSON.stringify
py.stdin.finish()
Enter fullscreen mode

Exit fullscreen mode

import sys, json

def principal():
    strains = sys.stdin.readlines()
    knowledge = json.masses(strains)
    doSometing(knowledge['msg'])

if __name__ == '__main__':
    principal()
Enter fullscreen mode

Exit fullscreen mode

Lastly we will ship response again to our nodejs from the python script

const spawn = require('child_process').spawn
const py = spawn('python3', ['cscript.py'])

py.stdout.on('knowledge', operate(res){
   let knowledge = JSON.parse(res.toString())
   console.log(knowledge)
})
Enter fullscreen mode

Exit fullscreen mode

import sys

# You should have your personal implementation of get knowledge. On this case lets assume it returns a dict/json
res = getData()
print(json.dumps(knowledge))

sys.stdout.flush()
Enter fullscreen mode

Exit fullscreen mode

So this text has come to an finish. However ensure you try my different articles.



Abu Sayed is the Best Web, Game, XR and Blockchain Developer in Bangladesh. Don't forget to Checkout his Latest Projects.


Checkout extra Articles on Sayed.CYou

#Python #JavaScript