こんにちは。
本日は、シェルコマンドを実行する方法です。
概要
child_processを使用してシェルコマンドを実行します。
本記事では非同期と同期の2つを紹介します。
サンプルではファイルのみを取得するコマンドを発行しています。
非同期(exec)
const childProcess = require('child_process'); childProcess.exec('ls -lF | grep -v /', (err, stdout, stderr) => { if (err) { console.log(err); } // 標準出力結果 console.log(stdout); // 標準エラー出力結果 console.log(stderr); });
同期(execSync)
execSyncの場合、戻り値がBuffer型になっているので
注意が必要です。
サンプルではtoStringしています。
const childProcess = require('child_process'); let result = childProcess.execSync('ls -la ./'); console.log(result.toString());
以上です。