Take the 2-minute tour ×

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.


var sys = require('sys');
var http = require('http');
var HOST = '';
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'});
}).listen(PORT, HOST);

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


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
Data: 123

But I only the following in the browser:


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


share|improve this question

1 Answer 1

up vote 1 down vote accepted

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

child.on('close', function() {
share|improve this answer
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')? –  user3144462 Dec 31 '13 at 19:33
Move the res. calls into the function you're passing to run() otherwise they get called before the callback completes. –  Stuart Dec 31 '13 at 19:35
That was it, in combination with your previous comment. Thanks much! –  user3144462 Dec 31 '13 at 19:38

Your Answer


