您將需要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
>您將需要exec的異步/回調版本。 – user3311045
我實際上正試圖同步做到這一點。我瞭解到,我正以這種方式非常認真地抓住這些吸管。異步方法很好。感謝您的意見。 – user3311045
@ user3311045 - 如果你接受了我的回答,那將會很棒。但是,如果您想要支持能夠通過同步選項瞭解如何執行此操作的人,那很酷。我試圖通過'execSync'找出它,但我認爲沒有辦法。 – bbuckley123