I have a nodejs backend called a python script and then used stdout.flush to send the json to nodejs backend.
at the end of the python script:
sys.stdout.write(json.dumps(json_dict))
sys.stdout.flush()
on nodejs backend:
app.get('/records', (req, res) => {
const { spawn } = require('child_process');
const pyProg = spawn('python', ['script.py']);
pyProg.stdout.on('data', function (data) {
console.log(data.toString());
return res.json({ success: true, data });
});
})
Then I used fetch to get the data in frontend:
fetch('/records')
.then((response) => response.json())
.then((response) => {
if (response.success && response.data) {
console.log(response.data);
when I print the response.data in console i got is like this:
{type: 'Buffer', data: Array(389)}
How can I get the json_dict in json format or string format in the frontend so i can display the content? All i got are 389 numbers like this:
data:
Array(389)
[0 … 99]
[100 … 199]
[200 … 299]
[300 … 388]
length: 389
I tried many ways to convert the Array(389) but not working. Thanks
CodePudding user response:
On the backend, you can send the data as a string to the frontend
app.get('/records', (req, res) => {
const { spawn } = require('child_process');
const pyProg = spawn('python', ['script.py']);
pyProg.stdout.on('data', function (data) {
// Parse the string as JSON
const jsonData = JSON.parse(data.toString());
// Send the JSON object to the frontend
return res.json({ success: true, data: jsonData });
});
});