0

I'm following the posts here but when I go to localhost:3000, the page is blank. I've tried to change my Python script path but that does not seem to work. It seems that it's not accessing the script1.py file. I'm not sure why.

NOTE: script1.py and index.js are both in the same directory.

Here is my index.js:

const express = require('express');
const {spawn} = require('child_process');
const app = express();
const port = 3000;

app.get('/', (req, res) => {
  var dataToSend;
  const python = spawn('python', ['script1.py']);
  python.stdout.on('data', function (data) {
    dataToSend = data.toString();
  });
  python.on('close', (code) => {
    console.log(`child process close all stdio with code ${code}`);
    res.send(dataToSend)
  });
});

app.listen(port);

Here is my script1.py:

print('Hello from python')

And http://localhost:3000/ is completely blank (though it is being run) but it's not displaying 'Hello from python'.

Tomalak
  • 332,285
  • 67
  • 532
  • 628
Katie Melosto
  • 1,047
  • 2
  • 14
  • 35

1 Answers1

0

this is how it worked for me: app.js file:

const spawn = require("child_process").spawn;
const pythonProcess = spawn('python', ["./p1.py"]);
const http = require('http');

let pythonData = null;
pythonProcess.stdout.on('data', (data) => {
    pythonData = data.toString();
});

let app = http.createServer((req, res) => {
    // Set a response type of plain text for the response
    
    if(req.url === "/getPyt") {
        res.end(JSON.stringify(pythonData));
    }

    if(req.url === "/") {
        res.writeHead(200, { 'Content-Type': 'text/plain' });
        res.end("Hello there");
    }
});

// Start the server on port 3000
app.listen(3000, 'localhost');
console.log('Node server running on port 3000');

p1.py :

import sys

print("Hello there")
sys.stdout.flush()

I think what you missed is that ./ refferencing python file. I've commented sys.stdout.flush() inside p1.py and it's also working.