【问题标题】:Nodejs child process stdin.write no callbackNodejs子进程stdin.write没有回调
【发布时间】:2016-11-18 06:08:23
【问题描述】:

我已经生成了一个“保持活动状态”的 nodejs 子进程,它会响应传入的 http get 请求。

var spawn = require("child_process").spawn;
var child = spawn("long_live_exe");

app.get("/some_request", function(req, res){
     child.stdin.write("some_request\n");
     res.send("task completed");
 });

理想情况下,我想发回响应,基于child.stdout,像这样

 app.get("/some_request", function(req, res){
     child.stdin.write("some_request\n");
     child.stdout.on('data', function(result){
            res.send(result);
     });
 });

问题在于,对于每个请求,stdout.on 事件函数都会再连接一次。这不是一件坏事吗?

不知怎的,如果我能从stdin.write得到回调函数,想象一下我能不能写代码

 app.get("/some_request", function(req, res){
     child.stdin.write("some_request\n", function(reply){
            res.send(reply); 
      });

 });

问题是如何将child.stdout.on 反馈给 http 请求回调?

【问题讨论】:

    标签: node.js


    【解决方案1】:

    使用once

    app.get("/some_request", function(req, res){
       child.stdin.write("some_request\n");
       child.stdout.once('data', function(result){
         res.send(result);
       });
    });
    

    【讨论】:

      【解决方案2】:

      最有效的方法是使用stream-pipe

      app.get("/some_request", function(req, res){
        child.stdin.write("some_request\n")
        child.stdout.pipe(res)
      })
      

      如果您需要依赖 stdout 发射器上的单次写入,请使用 res.end insted 或 res.send 以便在之后立即刷新响应;)

      app.get("/some_request", function(req, res){
        child.stdin.write("some_request\n")
        child.stdout.once('data', res.end)
      })
      

      【讨论】:

        猜你喜欢
        • 2014-02-04
        • 2016-01-23
        • 1970-01-01
        • 2017-05-14
        • 1970-01-01
        • 2013-10-22
        • 1970-01-01
        • 1970-01-01
        • 2019-07-01
        相关资源
        最近更新 更多