2017-09-13 157 views
0

當我想在我的節點上運行服務apache2狀態時,我注意到非常奇怪的行爲。這是代碼:如何檢查停止服務的服務狀態

app.post('/getStatus', jsonParser, function(req,res){ 

    exec("service apache2 status", function(err, stdout){ 
    if(err) throw err; 
    var statuspmtatmp = /Active: [a-z]* [\(][a-z]*[\)]/g.exec(stdout.toString())[0]; 

    res.json(statuspmtatmp); 
    }); 

}); 

當我運行時的apache運行一切正常,但是當我停止Apache和他們我嘗試檢查狀態,我得到錯誤的命令:

Error: Command failed: /bin/sh -c service apache2 status 
at ChildProcess.exithandler (child_process.js:213:12) 
at emitTwo (events.js:87:13) 
at ChildProcess.emit (events.js:172:7) 
at maybeClose (internal/child_process.js:821:16) 
at Socket.<anonymous> (internal/child_process.js:319:11) 
at emitOne (events.js:77:13) 
at Socket.emit (events.js:169:7) 
at Pipe._onclose (net.js:469:12) 

什麼是錯的?爲什麼當Apache運行一切正常?

回答

0

您檢查錯誤,並在此行引發錯誤:

if(err) throw err; 

所以執行停止並拋出一個錯誤

if(err){ 
    //code to handle the error 
} 

正如你在node docs閱讀:

If a callback function is provided, it is called with the arguments (error, stdout, stderr). On success, error will be null. On error, error will be an instance of Error. The error.code property will be the exit code of the child process while error.signal will be set to the signal that terminated the process. Any exit code other than 0 is considered to be an error.

+0

爲什麼在這一行?爲什麼不通過我看到的粗壯的代碼我有信息說服務被甩了? – cyprian

+0

我更新了我的回答 – aaron0207

+0

工作?我添加了一些清晰的答案,也許現在更清楚 – aaron0207