I have written a program to be run by my Node.js server to interact with a python script (source: https://github.com/extrabacon/python-shell), which successfully sends data to the script and receieves the returned value.
What is returned (message)
(in pyshell.on
) is a json
, which only appears to be local to the function passed in, however I would like to use this data elsewhere in my program outside this function.
Being new to javascript I initially tried to just set ret_val = message;
to no avail, have tried changing the type (python side) to a string (still no success), and finally converting json to string and parsing to ret_val (as it is now) ret_val = JSON.parse(JSON.stringify(message));
. Unfortunately none of these methods work, as ret_val remains undefined, despite message clearly containing the data i need as an object (checked using typeof). I would like to know either the correct way to copy the contents of the message
variable into ret_val
to be later returned, or possibly the correct way to get the message
data if I am using this module incorrectly.
SEE below for logs
UPDATE: Full script containing issue, occurs in function run_py_script
when setting ret_val
.
var express = require('express');
var router = express.Router();
var PythonShell = require('python-shell');
var options = {
mode: 'json'
};
var rain_data;
function run_py_script(data, callback){
var pyshell = new PythonShell('dummy.py', options);
var ret_val;
pyshell.send("dummy data"); // change to data
pyshell.on('message', function(message){
console.log(message);
rev_val = message;
//console.log(ret_val["willCollide"]);
});
pyshell.end(function(err){
if (err) {
console.log("hi");
}
return err ? callback(null) : callback(null, ret_val);
});
}
/* GET rain_track data. */
router.get('/', function(req, res, next) {
run_py_script(null, function(err, rain_data) {
console.log(err);
console.log(rain_data);
if (err){ console.log("error in python script" ); return res.json(null); }
if (rain_data == null){
console.log("Error: data is null or undefined");
}
res.json(rain_data);
})
});
module.exports = router;
Logs:
{ willCollide: 1, time: 6000, strength: 'NA' }
null
undefined
Error: data is null or undefined
GET /rain_track 200 62.778 ms - -