[英]Nodejs child process stdin.write no callback
I have spawned a "keep alive" nodejs child process that does things in response to incoming http get request. 我生成了一个“保持活动”的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");
});
Ideally, I'd like to send back response, based on child.stdout
, like this 理想情况下,我想基于
child.stdout
发送回响应,如下所示
app.get("/some_request", function(req, res){
child.stdin.write("some_request\n");
child.stdout.on('data', function(result){
res.send(result);
});
});
The problem is that per each request, stdout.on
event function is wired one more time. 问题在于,对于每个请求,
stdout.on
事件函数stdout.on
连接一次。 Isn't it a bad thing to do? 这不是一件坏事吗?
Somehow, if I can get callback function from stdin.write
, imagine if I can write code 以某种方式,如果我可以从
stdin.write
获得回调函数,请想象我是否可以编写代码
app.get("/some_request", function(req, res){
child.stdin.write("some_request\n", function(reply){
res.send(reply);
});
});
The question is how to feed child.stdout.on
back to a http request callback? 问题是如何将
child.stdout.on
反馈回http请求回调?
Use once
: 使用
once
:
app.get("/some_request", function(req, res){
child.stdin.write("some_request\n");
child.stdout.once('data', function(result){
res.send(result);
});
});
The most efficient way to accomplish this is by using a stream-pipe : 实现此目的的最有效方法是使用流管道 :
app.get("/some_request", function(req, res){
child.stdin.write("some_request\n")
child.stdout.pipe(res)
})
If you need to rely on a single write on the stdout
emitter use res.end
insted of res.send
in order to flush the response right after ;) 如果您需要对
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.