2

I start Python programs via Node.js and send a request to the server. After the Python program has run, I want to output the data on the client side. Python takes a long time, but it will stdout the data sometime.

After some time I am getting following error message in your browser:

GET http://localhost:4200/api/test net::ERR_EMPTY_RESPONSE core.js:1673 ERROR HttpErrorResponse {headers: HttpHeaders, status: 0, statusText: "Unknown Error", url: null, ok: false, …}

But my Python program went through.

I tried with res.end(), res.send(200).json() and res.send() but I am getting the same problem

server.ts

import app from './app';
import { Database } from './database';

const PORT = 8000;

Database.connect();

app.listen(PORT, () => {
  console.log('Express server listening on port ' + PORT);
});

app.timeout = 12000000000;

Node.js route.ts

app.route('/api/test').get((req: Request, res: Response) => {
  const spawn = require('child_process').spawn;
  const ls = spawn('python', [__dirname + '/getPosts.py']);
  let inData;
  ls.stdout.on('data', (chunk) => {
    inData = chunk.toString().replace('\n', '').split(',');
  });

  ls.stderr.on('data', (chunk) => {
    console.log(`stderr: ${chunk}`);
  });

  ls.on('close', (code) => {
    res.json(inData[0]); // -> ['True']
  });
});

Angular service.ts

  callData() {
    return this._http.get<any>(`${'/api/test'}`, {}).pipe(map((res: any) => {
      return res;
    }));
  }
0

1 Answer 1

0

I believe your problem in this block

app.route('/api/test').get((req: Request, res: Response, next: any) => {

        |
        |
        |
        |
       \ /
        .

  (1)     // you receive request from front-end.
  (2)     // then excute your paython script/

      const spawn = require('child_process').spawn;
      const ls = spawn('python', [__dirname + '/getPosts.py']);
      let inData;

      // start listning to events for stdout. 

      ls.stdout.on('data', (chunk) => {
        inData = chunk.toString().replace('\n', '').split(',');
      });

      ls.stderr.on('data', (chunk) => {
        console.log(`stderr: ${chunk}`);
      });

      ls.on('close', (code) => {
        res.json(inData[0]); // -> ['True']

        (6) I got data here. send it as json
        (7) Huh!!! where is the connection.

      });


   (3)    // your callback is waiting you to responed
   (4)    // nothing happen 
   (5)    // connection closed.

});




             FIX
// npm install --save express-async-handler
// of use this
const asyncUtil = fn =>
function asyncUtilWrap(...args) {
  const fnReturn = fn(...args)
  const next = args[args.length-1]
  return Promise.resolve(fnReturn).catch(next)
}


  app.route('/api/test', asyncHandler(async (req, res, next) => {
    const inData = await processMydata();
    res.json(inData[0])
})) 

async processMydata(){
      const spawn = require('child_process').spawn;
      const ls = spawn('python', [__dirname + '/getPosts.py']);
      const promise  =  new Promise(function(resolve, reject){
        ls.stdout.on('data', (chunk) => {
          const inData = chunk.toString().replace('\n', '').split(',');
          resolve(inData)
        });
      }) 
    return await promise;;
}
Sign up to request clarification or add additional context in comments.

2 Comments

Awesome great. I just add async() insted of asyncHandler. It seems to be working. Or why I should use the asyncHandler?
That's fine if it works you don't need asyncHandler

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.