spawnhtml
child_process.spaen會返回一個帶有stdout和stderr流的對象。你能夠經過stdout流來讀取子進程返回給Node.js的數據。 stdout擁有’data’,’end’以及通常流所具備的事件。當你想要子進程返回大量數據給Node時,好比說圖像處理,讀取二進制數 據等等,你最好使用spawn方法 child_process.spawn方法是「異步中的異步」,意思是在子進程開始執行時,它就開始從一個流總將數據從子進程返回給Node
var cp = require('child_process'); //spawn var ls = cp.spawn('ls'/*command*/, ['-lh', '/usr']/*args*/, {}/*options, [optional]*/); ls.stdout.on('data', function (data) { console.log('stdout: ' + data); }); ls.stderr.on('data', function (data) { console.log('stderr: ' + data); }); ls.on('exit', function (code) { console.log('child process exited with code ' + code); });
exec異步
child_process.exec方法是「同步中的異步」,意思是儘管exec是異步的,它必定要等到子進程運行結束之後而後一次性返回全部的buffer數據。
若是exec的buffer體積設置的不夠大,它將會以一個「maxBuffer exceeded」錯誤失敗了結
child_process.exec方法會從子進程中返回一個完整的buffer。默認狀況下,這個buffer的大小應該是200k。
若是子進程返回的數據大小超過了200k,程序將會崩潰,同時顯示錯誤信息「Error:maxBuffer exceeded」。
你能夠經過在exec的可選項中設置一個更大的buffer體積來解決這個問題,可是你不該該這樣作,由於exec原本就不是用來返回不少數據的方法。
對於有不少數據返回的狀況,你應該使用上面的spawn方法。那麼exec到底是用來作什麼的呢?咱們可使用它來運行程序而後返回結果的狀態,而
不是結果的數據
var cp = require('child_process'); var ls = cp.exec('ls -lh /usr', {}/*options, [optional]*/); ls.stdout.on('data', function (data) { console.log('stdout: ' + data); }); ls.stderr.on('data', function (data) { console.log('stderr: ' + data); }); ls.on('exit', function (code) { console.log('child process exited with code ' + code); });
轉自 http://yijiebuyi.com/blog/3ec57c3c46170789eed1aa73792d99e5.htmlui