Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

411
Vistas
Node.js send input text to python script for processing and writing the output on a div on the same page

I am trying to take text from an HTML input field and send it via POST-request to a python script for processing (I am using child process).

Right now, I am just sending the processed data to the response and overwriting the index.html, but I would like to just write the output of the python script into a text field under the input field in the same endpoint ("/").

Is there a way of doing this without having to re-render the entire HTML with just the new text added to it?

server.js:

const express = require("express");
const { spawn } = require("child_process");
const path = require("path");
const bodyParser = require("body-parser");

const router = express()

const app = express();
const port = 3000;

app.use(bodyParser.urlencoded({extended:true}));


app.get("/", (req, res) => {
    res.sendFile(path.join( __dirname+'/index.html'));
});

app.post("/", (req, res) => {

    // This is where the text field data is parsed into the python script
    const python = spawn("python", ["script.py", req.body.sentence]);
    

    python.stdout.on("data", function (data) {
        processed_data = data.toString();
    });
    python.stderr.on("data", data => {
        console.error(`stderr: ${data}`);
    })
    python.on("exit", (code) => {
        
        // Something else here possibly?
        res.send(processed_data);

    });
})

app.listen(port, () => console.log(`App listening on port ${port}!`));

index.html:

<form method="POST" action="/">
    <fieldset>
        <label>Write a sentence:</label>
        <input type="text" id="sentence" name="sentence" required>
        <br><br>
        <button type ="submit">Run</button>
        <br><br>
        <textfield id=output_field><textfield>
    </fieldset>
</form>

script.py can really do anything here:

import sys

sentence = sys.argv[1]
print(sentence , " this is stuff added to the sentence")

sys.stdout.flush()
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

index.html

   <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
 
        <fieldset>
            <label>Write a sentence:</label>
            <input type="text" id="sentence" name="sentence" required>
            <br><br>
            <button id='buttonFetch'>Run</button> 
            <br><br>
            <textfield id="output_field"><textfield>
        </fieldset>
 
<script>
const button = document.querySelector("#buttonFetch")
button.addEventListener("click", () => {

 const sentence = document.querySelector("#sentence").value
  fetch("http://localhost:3000/", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
        sentence
    }),
  })
    .then(res => res.text())
    .then(data => {
        console.log(data)
        const output_field = document.querySelector("#output_field")
        output_field.textContent = data
    })
    .catch(e => {
      console.error(e.error)
    })
})
</script>
</body>
</html>

server.js (I removed bodyParser and add express.json())

'use strict'

const express = require("express");
const { spawn } = require("child_process");
const path = require("path");
//const bodyParser = require("body-parser");

const router = express()

const app = express();
const port = 3000;

app.use(express.json())

//app.use(bodyParser.urlencoded({extended:true}));

app.get("/", (req, res) => {
    res.sendFile(path.join( __dirname+'/index.html'));
});

app.post("/", (req, res) => {
    console.log(`req.body.sentence: ${req.body.sentence}`)

    // This is where the text field data is parsed into the python script
    const python = spawn("python", ["script.py", req.body.sentence]);
    
    let processed_data = ''

    python.stdout.on("data", function (data) {
         processed_data = data.toString();
    });
    python.stderr.on("data", data => {
        console.error(`stderr: ${data}`);
    })
    python.on("exit", (code) => {
        // Something else here possibly?
        console.log(processed_data)
        res.send(processed_data);
    });
})

app.listen(port, () => console.log(`App listening on port ${port}!`));
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda