繁体   English   中英

Node.js子进程stdin.write没有回调

[英]Nodejs child process stdin.write no callback

我生成了一个“保持活动”的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事件函数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请求回调?

使用once

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

实现此目的的最有效方法是使用流管道

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

如果您需要对stdout发射器进行一次写操作,请使用res.send res.end以便在之后刷新响应;)

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM