I am trying the following code to get desired python output and store it and also send the result as http response from Node.js. Here is my code
This the the python test.py file
import sys
print("Output from Python")
print("First name: " + sys.argv[1])
print("Last name: " + sys.argv[2])
This is Node.js spawn methods
testRoute: async(req, res, next) => {
var output="";
var child = spawn('python', [`${process.cwd()}/pyCodes/test.py`,
'Itachi',
'Uchiha'
]);
child.stdout.setEncoding('utf8');
await child.stdout.on('data', (data) => {
data = data.toString();
output += data;
});
child.stderr.on("data", (data) => {
data = data.toString();
output += data;
});
child.on("error", (error) => {
error = error.toString();
output += error;
});
child.stderr.pipe(process.stderr);
cosnsole.log('output: ', output) // this shows output as empty
child.on("close", (code) => {
return res.send({
statusCode: 200,
status: 'Success',
data: output, // the output is like this : "Output from Python\r\nFirst name: Itachi\r\nLast name: Uchiha\r\n"
});
});
}
But the output only prints in console/ insides spawn methods. If I access the output from outside spawn methods it shows empty. How can I store the output from python code in some variable? Also if I directly do res.send() inside child.on('close') the resultant string contains special characters like '\r','\n' etc... how can i avoid that? I even tried using JSON.parse but it throws error finding unwanted token at position 0 . Please if anyone can let me know how to get proper output in res.send() and also how to store output in variable even as JSON?