0

I'm able to spawn a Python child_process and write the data returned from Python to the console in Node. However, I'm not able to return the data in a callback function in Node. I’m thinking this is because the callback function is asynchronous, so the server returns the result to the browser before the callback returns.

test_server.js

var sys = require('sys');
var http = require('http');
var HOST = '127.0.0.1';
var PORT = 3000;

function run(callBack) {
    var spawn = require('child_process').spawn,
        child = spawn('python',['test_data.py']);
    var resp  = "Testing ";

    child.stdout.on('data', function(data) {
        console.log('Data: ' + data); // This prints "Data: 123" to the console
        resp += data; // This does not concat data ("123") to resp
    });

    callBack(resp) // This only returns "Testing "
}

http.createServer(function(req, res) {
    var result = '';

    run(function(data) {
        result += data;
    });

    res.writeHead(200, {'Context-Type': 'text/plain'});
    res.end(result);
}).listen(PORT, HOST);

sys.puts('HTTP Server listening on ' + HOST + ':' + PORT);

test_data.py

import sys

out = '123';
print out

When I run: node test_server.js, then hit it in a browser, I get the following in the console:

c:\>node test_server.js
HTTP Server listening on 127.0.0.1:3000
Data: 123

But I only the following in the browser:

Testing 

Could someone explain how I can wait for the callback function to return before continuing?

Thanks.

1 Answer 1

1

You need to hook your callback up to the close event from the child_process.

child.on('close', function() {
    callBack(resp);
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for the reply. When I add the following code, and comment-out the original callBack(resp), I don't get anything in the browser. child.on('close', function() { callBack(resp); }); Could you explain how to trigger child.on('close')?
Move the res. calls into the function you're passing to run() otherwise they get called before the callback completes.
That was it, in combination with your previous comment. Thanks much!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.