ウェブエンジニア珍道中

日々の技術的に関する経験を書いていきます。脱線もしますが助けになれば幸いです。

Node.js上でのlinuxコマンドの叩き方

Node.js上でlinuxコマンドの叩き方を備忘録として残します。

実行方法

child_processをrequireしてexecメソッドを使います。

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

exec("echo 'hogehoge'", (error, stdout, stderr) => {
  if (error) {
    console.log(error);
    console.log(stderr);
  }
  console.log(stdout);
});

execメソッドには第一引数には叩くコマンドを文字列で、第二引数にはコマンドの結果が返ってきた時に実行する関数を与えます。この関数はさらに引数としてnode側のエラーが入ったerror, 標準出力のstdout, 標準エラー出力のstderrを受け取ります。変数名は任意です。

errorはコマンドが無事終了した場合はnullなので、これを用いてエラーハンドリングをしています。

# 実行結果
hogehoge

同期処理での実行方法

ただ上記の方法だと、非同期で処理が行われるため実行結果を変数に入れて使用したいと言う場合に上手く動作しません。

例:

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

var result = "";
exec("echo hogehoge", (error, stdout, stderr) => {
  if (error) {
    console.log(error);
    console.log(stderr);
  }
  result = stdout;
});
console.log("-----------")
console.log(result)
console.log("-----------")
# 実行結果
-----------

-----------

これはecho hogehogeの結果が返って変数に代入される前に下のconsole.logの評価がされて起きる現象です。

同期処理にしたい場合はexecではなくexecSyncを使いましょう。使い方は下記の通り。

const execSync = require('child_process').execSync;

var result = "";
result = execSync("echo hogehoge").toString();
console.log("-----------");
console.log(result);
console.log("-----------");

返り値を代入すれば良いです、返り値はBufferで普通には使えないのでtoString()してあげれば良いです。

# 実行結果
-----------
hogehoge

-----------

詳しいオプション等はこちら。

Child Process | Node.js v10.8.0 Documentation