素のJavaScriptからexeを実行する方法は以前やったが、やっぱりNode.jsから実行したい。

JavaScriptからexeを実行する
child_process.exec()
コマンドを非同期で実行する。実行結果はcallbackで受け取る。
Child process | Node.js v15.9.0 Documentation
Sample
sample.exe
を実行する。
var exec = require('child_process').exec
var sample = function () {
exec('/sample.exe', function(err, stdout, stderr) {
if (stdout) console.log('stdout', stdout)
if (stderr) console.log('stderr', stderr)
if (err !== null) console.log('err', err)
})
}
sample()
child_process.execSync()
コマンドを同期的に実行する。実行結果が戻り値になる。
Child process | Node.js v15.9.0 Documentation
Sample
sample.exe
を実行する。
const execSync = require('child_process').execSync
const stdout = execSync('/sample.exe')
console.log(stdout)
あとがき的な
child_process.execSync()
を使っていたが、stderr
を受け取れないのが気に食わなくて調べていたら、
https://ja.stackoverflow.com/questions/28527/node-js-%E3%81%AE-execsync-%E3%81%AE%E6%88%BB%E3%82%8A%E5%80%A4%E3%81%A7-stderr-%E3%82%92%E5%8F%97%E3%81%91%E5%8F%96%E3%82%8B%E6%96%B9%E6%B3%95
stderr
が必要でしたら、例えばspawnSync
を使う方がよいと思います。
と、書いてある記事を見つけた。
Child process | Node.js v15.9.0 Documentation
stderr
以外に何が違うのか見れてないので、そのうち試してみる。
コメント