🍃このブログは移転しました。
3秒後、自動的に移動します・・・。

Node.jsのchild_process.execの標準出力のオプション

なんてわかりにくいタイトル!でも忘れないようにメモ。

child_process.execで、OSのコマンドを実行し、その結果をNodeで処理したいとする。
その実行結果を「標準出力で受け取る」ときに、オプションが設定できるんですね。

参考:Child Process Node.js v0.10.2 Manual & Documentation

child_process.exec

子プロセスを起動して、そこでOSのコマンドを実行するやつ。

var exec = require('child_process').exec;

exec('tree ~/git/myApp/ -L 3', function (error, stdout, stderr) {
    if(stdout){
        console.log('stdout: ' + stdout);
    }
    if(stderr){
        console.log('stderr: ' + stderr);
    }
    if (error !== null) {
      console.log('Exec error: ' + error);
    }
});

たとえばこの例だと、コンソールに、

tree ~/git/myApp/ -L 3

の実行結果が標準出力として表示されるはずです。

ただtreeコマンドみたく、やたらと出力するものがある処理の場合、以下のエラーが出るときがあります・・。

Error: maxBuffer exceeded.

標準出力のバッファのリミットを超えると、プロセスがkillされる+標準出力が途中で切れます。
実はドキュメントにも書いてますね。

maxBuffer specifies the largest amount of data allowed on stdout or stderr - if this value is exceeded then the child process is killed.

というわけで、大量の標準出力を扱いたい、そんなときには!

第二引数にオプションを

以下がオプションとして設定できます。

// Defaults.
{
  encoding: 'utf8',
  timeout: 0,
  maxBuffer: 200*1024,
  killSignal: 'SIGTERM',
  cwd: null,// = CurrentWorkingDirectory
  env: null// = EnvironmentVariables
}

何も設定しない場合は、以下の内容がデフォルトで適用されてます。

最初の例にオプションを指定すると、

var exec = require('child_process').exec;

exec('tree ~/git/myApp/ -L 3', {maxBuffer: 400*1024}, function (error, stdout, stderr) {
    if(stdout !== null){
        console.log('stdout: ' + stdout);
    }
    if(stderr !== null){
        console.log('stderr: ' + stderr);
    }
    if (error !== null) {
      console.log('Exec error: ' + error);
    }
});

これで安心というわけ。