Saturday, October 10, 2020

Python on Node.js

most generic, not most efficient...  simple
 
How to Run a Python script from Node.js | by Petros Koulianos | The Startup | Medium

const express = require('express')
const {spawn} = require('child_process');

const app = express()
const port = 3000
app.get('/', (req, res) => {
 
 var dataToSend;
 // spawn new child process to call the python script
 const python = spawn('python', ['script1.py']);
 // collect data from script
 python.stdout.on('data', function (data) {
  console.log('Pipe data from python script ...');
  dataToSend = data.toString();
 });
 // in close event we are sure that stream from child process is closed
 python.on('close', (code) => {
 console.log(`child process close all stdio with code ${code}`);
 // send data to browser
 res.send(dataToSend)
 });
 
})
app.listen(port, () => console.log(`Example app listening on port 
${port}!`))

more efficient, direct calls

Bridging Node.js and Python with PyNode to Predict Home Prices | The Coding Interface

PyNode instead fully bridges the two environments by utilizing both the Node.js and Python C / C++ API bindings to seamlessly interoperate from Node.js to Python and back. In this way JavaScript function parameters are converted to Python types during the call of specified Python functions all the while converting returned pure Python types to JavaScript types.... this is a significant improvement over streaming and parsing data as it comes back from Python via standard output affording a layer of type safety at the interface between the two languages.

No comments: