2015-09-30 47 views
11

下面顯示的代碼片段非常適合獲取對系統命令stdout的訪問。有什麼方法可以修改此代碼,以便還可以訪問系統命令的退出代碼以及系統命令發送到stderr的任何輸出?node.js - 訪問系統命令的退出代碼和stderr

#!/usr/bin/node 
var child_process = require('child_process'); 
function systemSync(cmd) { 
    return child_process.execSync(cmd).toString(); 
}; 
console.log(systemSync('pwd')); 

回答

6

您將需要exec的異步/回調版本。有3個值返回。最後兩個是stdout和stderr。另外,child_process是一個事件發射器。聽聽exit事件。回調的第一個元素是退出代碼。 (從語法明顯,你需要使用節點4.1.1得到下面的代碼工作,因爲寫的)

const child_process = require("child_process") 
function systemSync(cmd){ 
    child_process.exec(cmd, (err, stdout, stderr) => { 
    console.log('stdout is:' + stdout) 
    console.log('stderr is:' + stderr) 
    console.log('error is:' + err) 
    }).on('exit', code => console.log('final exit code is', code)) 
} 

嘗試以下操作:

`systemSync('pwd')` 

`systemSync('notacommand')` 

,您將獲得:

final exit code is 0 
stdout is:/ 
stderr is: 

其次:

final exit code is 127 
stdout is: 
stderr is:/bin/sh: 1: notacommand: not found 
+0

>您將需要exec的異步/回調版本。 – user3311045

+0

我實際上正試圖同步做到這一點。我瞭解到,我正以這種方式非常認真地抓住這些吸管。異步方法很好。感謝您的意見。 – user3311045

+0

@ user3311045 - 如果你接受了我的回答,那將會很棒。但是,如果您想要支持能夠通過同步選項瞭解如何執行此操作的人,那很酷。我試圖通過'execSync'找出它,但我認爲沒有辦法。 – bbuckley123

5

您可能會在LSO使用child_process.spawnSync(),因爲它返回得多:

return: 
pid <Number> Pid of the child process 
output <Array> Array of results from stdio output 
stdout <Buffer> | <String> The contents of output[1] 
stderr <Buffer> | <String> The contents of output[2] 
status <Number> The exit code of the child process 
signal <String> The signal used to kill the child process 
error <Error> The error object if the child process failed or timed out 

所以,你要尋找的退出代碼將是ret.status.

20

你並不需要做的是異步。您可以保留您的execSync功能。

將它包裹一試,傳遞給catch(e)塊的Error將包含您正在查找的所有信息。

var child_process = require('child_process'); 

function systemSync(cmd) { 
    try { 
    return child_process.execSync(cmd).toString(); 
    } 
    catch (error) { 
    error.status; // Might be 127 in your example. 
    error.message; // Holds the message you typically want. 
    error.stderr; // Holds the stderr output. Use `.toString()`. 
    error.stdout; // Holds the stdout output. Use `.toString()`. 
    } 
}; 

console.log(systemSync('pwd')); 

如果沒有引發錯誤,則:

  • 狀態是保證0
  • 標準輸出什麼用功能
  • 標準錯誤恢復幾乎是絕對空的,因爲它是成功的。

在非常非常罕見的事件中,命令行可執行文件返回一個stderr並且以狀態0(成功)退出,並且您想要讀取它,您將需要異步函數。

+0

完美!正是我需要的! – born2net

+1

:)啊,幫助別人的深厚幸福 –

+2

謝謝lance - 創建了這個npm模塊 - shelljs.exec - 它將你放置在這裏的所有邏輯包裝成一個漂亮的小包 - 乾杯:D – danday74