【发布时间】:2013-12-31 19:20:56
【问题描述】:
我能够生成 Python child_process 并将 Python 返回的数据写入 Node.js 中的控制台。但是,我无法在 Node.js 的回调函数中返回数据。我在想这是因为回调函数是异步的,所以服务器在回调返回之前将结果返回给浏览器。
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
当我运行:node test_server.js,然后在浏览器中点击它,我在控制台中得到以下信息:
c:\>node test_server.js
HTTP Server listening on 127.0.0.1:3000
Data: 123
但我在浏览器中只有以下内容:
Testing
谁能解释我如何等待回调函数返回后再继续?
谢谢。
【问题讨论】:
标签: node.js