const
exec = require(
'child_process'
).exec;
exec(
'ls -la ./'
, (err, stdout, stderr) =>
{
if
(err)
{
console.log(err);
}
console.log(stdout);
exec関数は非同期関数であり、callbackに渡されるのは、err、標準出力文字列、
標準エラー出力
文字列です。
また、同期的に処理を実行したい場合にはexecSyncが利用できます。
const
execSync = require(
'child_process'
).execSync;
const
result = execSync(
'ls -la ./'
);
console.log(result);
execSyncの返り値はBufferなので注意しましょう。
$ node test.js
<Buffer 74 6f 74 61 6c 20 38 30 0a ... >
出力結果を処理したい場合にはtoString()などを利用しましょう。
const
result = execSync(
'ls -la ./'
).toString();
$ node test.js
total 10
drwxr-xr-x 17 user test 578 4 24 17:17 .
drwxr-xr-x 14 user test 476 4 17 05:02 ..
-rw-r--r--@ 1 user test 6148 3 27 10:49 file1
-rw-r--r-- 1 user test 188 1 21 12:55 file2
詳しい仕様は公式ドキュメントを参照ください。
Child Process Node.js v6.1.0 Manual & Documentation