In the backend, I have a python program(vmstats.py) that stores string data in vmonoff[]:
vmstats.py
import json
from proxys import ProxyServer
vmonoff = []
proxys = ProxyServer('XXXXXX','UUUUUU','PPPPPP')
for b in proxys.listeners:
if "MYVMNAME" in b.vname:
if b.stat=="UP":
vmonoff.append('./images/vm_on.png')
else:
vmonoff.append('./images/vm_off.png')
print('{:<10}'.format(b.vname), '{:<8}'.format('Status:'), '{:>6}'.format(b.stat))
response = json.dumps(vmonoff)
exec.controller.js
const {exec} = require('child_process');
const path = require('path');
const fs = require('fs');
const htmlFile = path.join(__dirname, '/index.html');
exports.executeReport = (req, res) => {
execute("python3 ./src/vmstats.py", res);
}
var responseObject = JSON.parse(response);
const execute = (command, res) => {
exec(command, (error, stdout, stderr) => {
if (error) {
res.send({result: `error: ${error.message}`});
return;
}
if (stderr) {
res.send({result: `stderr: ${stderr}`});
return;
}
createHtmlFile(stdout);
res.sendFile(htmlFile);
return;
});
}
const createHtmlFile = (stdout) => {
const rows = stdout.split('\n');
const content = `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Test</title>
</head>
<body>
<div >
<div style="text-align: center">
<h3>TEST</h3>
<br>
</div>
</div>
</body>
</html>`
fs.writeFileSync(htmlFile, content);
}
In the frontend(exec.controller.js), I tried to use:
var responseObject = JSON.parse(response)
But I got the ReferenceError: response is not defined
How can I transfer vmonoff[]
from python to the external express.js?
CodePudding user response:
First of all, it seems like your python script doesn't output anything to stdout
(normally done with something like print
), hence, Node JS have nothing to read from there.
Apart from that rows
variable inside the createHtmlFile
isn't used anywhere.
CodePudding user response:
in the python script you need to print the array:
response = json.dumps(vmonoff)
print(response)
and in the node script, stdout
is where you get the data, and there you can parse it and process it further:
const execute = (command, res) => {
exec(command, (error, stdout, stderr) => {
if (error) {
res.send({result: `error: ${error.message}`});
return;
}
if (stderr) {
res.send({result: `stderr: ${stderr}`});
return;
}
var responseObject = JSON.parse(stdout);
createHtmlFile(responseObject);
res.sendFile(htmlFile);
return;
});
}
and then in createHtmlFile
you can construct the HTML (for example, iterating array elements, or maybe using .join
instead of .split
, it's not clear what the HTML is supposed to look like..)