Reputation: 517
I am trying to execute this piece of node js code which execute a python script. Through this code works fine. but the response "running" and "finished" are displayed on front end immediately. "finshed" has to be displayed once the execution of python scripts gets completed.
app.post('/execute', function(request, response){
response.write("running");
console.log("executing")
var pyshell = new PythonShell('./python_codes/test.py')
pyshell.on('message', function (message) {console.log(message);});
pyshell.end(function (err) {if (err){throw err;};console.log('finished');});
response.write("finished");
response.end();
});
Upvotes: 1
Views: 1350
Reputation: 901
You should add your response inside the callback function
app.post('/execute', function(request, response){
response.setHeader('Connection', 'Transfer-Encoding');
response.setHeader('Content-Type', 'text/html; charset=utf-8');
response.write("running");
console.log("executing")
var pyshell = new PythonShell('./python_codes/test.py')
pyshell.on('message', function (message) {console.log(message);});
pyshell.end(function (err) {
if (err){
throw err;
};
console.log('finished');
response.write("finished");
response.end();
});
});
Upvotes: 1
Reputation: 7357
It happens because the PythonShell
class is asynchronous. What your code is doing is creating a PythonShell
object, storing it in variable pyshell
, and then adding a few events to the pyshell
object. It then directly continues to write "finished".
Because writing "finished" is not part of the callback for the end()
function, it happens right away. I see at least three things you can do:
response.write("finished"); response.end();
code to the pyshell.end
callback.Upvotes: 1