2017-08-19 44 views
0

創建我有這個節點的js代碼多child_processes在節點JS

var bat = null; 
app.post("/api/run", function(req,res) { 
    if(!bat) { 
     bat = spawn('cmd.exe', ['/c App.exe']); 
    } 

    if(req.body.success) { 
     bat.kill(); 
    } 

    bat.stdin.write(req.body.input+'\n'); 

    bat.stdout.on('data', function (data) { 
     console.log(data.toString()); 
     res.end(JSON.stringify({data: data.toString()})); 
    }); 

    bat.stderr.on('data', function (data) { 
     console.log(data.toString()); 
    }); 

    bat.on('exit', function (code) { 
     bat = null; 
     console.log('Child exited with code ' + code); 
    });  
}); 

此代碼是假設只創建一個子進程將運行exe文件。但經過3 Ajax請求時,子進程殺掉這是控制檯輸出:

Input NO: 1 You entered: input 1

Input NO: 2 You entered: input 2

Input NO: 2 You entered: input 2

Input NO: 3 You entered: input 3

Input NO: 3 You entered: input 3

Input NO: 3 You entered: input 3

Child exited with code 1
Child exited with code 1
Child exited with code 1

而應該每輸入一次登錄,有應該只有一個子進程。這段代碼有什麼問題。
任何幫助將不勝感激。謝謝

回答

2

你只是實例化一個進程,但你不斷掛鉤每個請求的新事件處理程序,這就是爲什麼你會得到重複輸出(3個請求= 3倍的消息)。

移動你.on呼叫if (!bat)聲明

if (!bat) { 
    bat = spawn('cmd.exe', ['/c App.exe']); 
    bat.stdout.on('data', function (data) { 
     console.log(data.toString()); 
     res.end(JSON.stringify({data: data.toString()})); 
    }); 
    bat.stderr.on('data', function (data) { 
     console.log(data.toString()); 
    }); 
    bat.on('exit', function (code) { 
     bat = null; 
     console.log('Child exited with code ' + code); 
    }); 
} 
bat.stdin.write(req.body.input+'\n'); 
+0

非常感謝。你救了我的日子 –

+0

@SaadMehmood不是所有英雄斗篷 – James

1

只有一個孩子的過程實際上裏面,但每個請求將增加一個exit事件偵聽器的子進程。所以第二次輸入顯示兩次,第三次顯示三次。並顯示Child exited 3次。

您可以嘗試以下方法。在子進程的時間

  • 添加事件偵聽器來創建
  • 刪除監聽後響應發送
  • 使用once,設置一個時間偵聽這些事件

希望這可以幫助你