2017-09-13 158 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