如何从nodejs中捕获子进程的响应

时间:2014-09-01 14:07:36

标签: node.js child-process

我正在尝试从主进程中的子进程中捕获一些响应。我可以在主进程中记录子进程的信息但无法捕获一些返回xyz响应。 这是主进程的代码:

var express  = require('express');
var app = express();
const
             fs = require('fs'),
             cp = require('child_process');
 app.get('/',onRequest );
    function onRequest(request, response) {
                var express  = require('express');
             var app = express();

            var child= cp.spawn('node' ,['./child_process/block.js'],filestreamCallback);
            child.stdout.on('data', function(data) {
                console.log('stdout: ==== ' + data);
            });
            child.stderr.on('data', function(data) {
                console.log('stdout: ' + data);
            });
            child.on('close', function(code) {
                console.log('closing code: ' + code);
            });
        function filestreamCallback() {
                response.writeHead(200, {'Content-Type': 'text/plain'});
                baflog.info("Reading Stream completed");
                response.write('Thanks for Your patience!\n');
                response.end();
            }
        }
        app.listen(5000);
        console.log('Server started');

Child process : block.js

        /*Keep waiting for 10 seconds*/

    console.log("Waiting for child Process (block.js) to complete......");
    var startTime = new Date().getTime();
    while (new Date().getTime() < startTime + 10000);
    ret_resp();
    var response = {status:'success'};
    function ret_resp(){
        return response;
    }
    console.log("Thank You for waiting......");

在控制台中我看到输出为: stdout ====:等待子进程(block.js)完成......  -punws-sohan

stdout:====感谢您的等待......

我看不到返回响应语句的输出 任何人都可以建议如何捕捉儿童过程的反应吗?

1 个答案:

答案 0 :(得分:2)

首先,busy循环占用了不必要的CPU时间。只需使用setTimeout()即可。例如:

setTimeout(function() {
  ret_resp();
  // ...
}, 10000);

其次,您不能指望return将返回的值神奇地写入父进程。试试这个:

// parent.js
var child = cp.fork('./child_process/block.js', [], { silent: true });
child.stdout.on('data', function(data) {
  console.log('stdout: ==== ' + data);
});
child.stderr.on('data', function(data) {
  console.log('stdout: ' + data);
});
child.on('message', function(msg) {
  console.log('message from child: ' + require('util').inspect(msg));
});
child.on('close', function(code) {
  console.log('closing code: ' + code);
});


// child.js
console.log('Waiting for child Process (block.js) to complete......');
setTimeout(function() {
  var response = {status:'success'};
  function ret_resp() {
    process.send(response);
  }
  ret_resp();
  console.log('Thank You for waiting......');
}, 10000);