Nodejssubprocessstdin.write没有callback

我产生了一个“keep alive”nodejssubprocess,用于响应传入的http请求。

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事件functionstdout.on连线。 这不是一件坏事吗?

不知何故,如果我可以从stdin.write获得callback函数,想象一下如果我可以编写代码

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

问题是如何将child.stdout.on返回给一个http请求callback?

使用once

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

最有效的方法是使用streampipe道 :

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

如果你需要依赖stdout器上的单个写操作,请使用res.end res.send以便在之后立即刷新响应;)

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