spawn
参考:
child_process.spawn(command[, args][, options]) – Child Process | Node.js Documentation [Official]
使い方
参考:
node の spawn に関して調べてみた – Qiita
Node.js で子プロセスを起動し、非同期的に実行する | 情報アイランド
Node.js で shell コマンドを叩く | PolyPeaceLight
Node.js Child Processes: Everything you need to know | freeCodeCamp.org
Working with stdout and stdin of a child process in Node.js | 2ality
子プロセスの出力を処理する
参考:
Node.js spawn child process and get terminal output live – Stack Overflow
pipe
参考:
detached
親プロセスが終了しても子プロセスを動かし続ける
const child = spawn(cmd, args, { detached: true, stdio: 'ignore' }) child.unref()
参考:
options.detached – Child Process | Node.js Documentation [Official]
Run node as background process from script running as child process – Stack Overflow
stdio
参考:
get stdout of all nested child process in node.js – Stack Overflow
async/await で非同期処理の結果を取得する
const { spawn } = require('child_process') function run(cmd) { return new Promise((resolve, reject) => { const command = spawn(cmd) let result = '' command.stdout.on('data', function(data) { result += data.toString() }) command.on('close', function(code) { return resolve(result) }) command.on('exit', function(code) { return resolve(result) }) command.on('error', function(err) { return reject(err) }) }) } async function runner() { try { const result = await run('ls') console.log(result) } catch (err) { console.log(`Error: ${err.message}`) } } runner()
参考:
Node.js の非同期処理のコールバック地獄を Promise、Generator、async/await を使って解決する – Qiita
Node.js Child Processes using spawn, exec, fork & async/await | zaiste.net
Writing a function to return spawn stdout as a string – Stack Overflow
How to wait for child_process.spawn execution with async/await? – Stack Overflow
await-spawn
参考:
ralphtheninja/await-spawn: child_process.spawn() wrapped in a Promise – GitHub