Search code examples
javascriptpythonnode.jschild-processspawn

Running python file using spawn in node js


I am trying to run python file on a post request from client(react js). Everything was working fine on the other windows 10 system. But when I tried to use it on another computer, now it is not working. On terminal, it is showing no error.

This is my server.js file:



const path = require("path");
const fs = require("fs");
const express = require("express");
const multer = require("multer");
const cors = require("cors");
const app = express();
const { spawn } = require("child_process");
const { request } = require("http");
const { response } = require("express");
const { stderr } = require("process");


function denoiseVideoByRaw(req, res) {
  
  var spawn = require("child_process").spawn;

  // raw audio
  var process = spawn("python", ["denoise_video.py"], {shell: true});

  process.stdout.on("data", function async(data) {
    // res.send(data.toString());
    console.log(data.toString());
  });
}
app.post("/denoise-video-by-raw", denoiseVideoByRaw);


app.listen(8000, () => {
  console.log("server is running on localhost:8000");
});


Solution

  • According to Node.js official documentation, you need to also capture stderr.

    Please apply these changes:

    var result = '';
    process.stdout.on('data', function (data) { // The callback function no need to be as async
        result += data.toString(); // each data is a chunk
    });
    

    stderr:

    process.stderr.on('data', function (data){
        result += data.toString();
    });
    
    

    final result:

    process.stdout.on('end',function (data){
        console.log(result);
    });