json - How to pass value of object to new global variable in JavaScript -
i have written program run node.js server interact python script (source: https://github.com/extrabacon/python-shell), sends data script , receieves returned value. returned (message)
(in pyshell.on
) json
, appears local function passed in, use data elsewhere in program outside function.
being new javascript tried set ret_val = message;
no avail, have tried changing type (python side) string (still no success), , converting json string , parsing ret_val (as now) ret_val = json.parse(json.stringify(message));
. unfortunately none of these methods work, ret_val remains undefined, despite message containing data need object (checked using typeof). know either correct way copy contents of message
variable ret_val
later returned, or possibly correct way message
data if using module incorrectly.
see below 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 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); }); } /* 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 null or undefined"); } res.json(rain_data); }) }); module.exports = router;
logs:
{ willcollide: 1, time: 6000, strength: 'na' } null undefined error: data null or undefined /rain_track 200 62.778 ms - -
Comments
Post a Comment