簡體   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