John John - 1 year ago 82
Node.js Question

How to include python script inside a NodeJS file?

Good day everyone,

Through recommendation of this community, I have install shelljs such as

npm install shelljs --save
into my app folder.

Now I am working out on how to implement it in my nodejs file.

Below is my nodejs file

var express = require('express');
var router = express.Router();
var COMPORT = 5;
var command = 'option1';

Below this i would like to include my python script

import serial
ser = serial.Serial()
ser.baudrate = 38400 #Suggested rate in Southco documentation, both locks and program MUST be at same rate
// COMPORT is a variable that stores an integer such as 6
ser.port = "COM{}".format(COMPORT)
ser.timeout = 10
#call the serial_connection() function

Hence, my question is how do you include this python script with the variables defined in nodejs included in the script in the same file as the nodejs.

This app that runs on nodejs will be package as an executable desktop app via electron.

Answer Source

I think it is the easiest way to run python script as child process.

const childProcess = require('child_process'),
      cmd = './ --opt=' + anyValueToPass;

childProcess.exec(cmd, function(err, stdout, stderr) {
  // command output is in stdout

Read more about child process at: Execute a command line binary with Node.js

In this way, you ned to care for command injection.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download