我有一个可执行文件,我想从NodeJS CLI应用程序调用它。这就是我到目前为止所做的:
var exec = require('child_process').exec;
exec(`./${name_of_executable}`, (err, stdout, stderr) => {
// I want to take user input on which this executable depends on
});
我该怎么做?
答案 0 :(得分:1)
如果您想传递一些参数,可以使用:
const { execFile } = require('child_process');
const child = execFile('node', ['--version'], (error, stdout, stderr) => {
if (error) {
throw error;
}
console.log(stdout);
});
如果要将自定义流作为标准输入传递给子进程,请使用spawn:
const { spawn } = require('child_process');
// Child will use parent's stdios
spawn('prg', [], { stdio: 'inherit' });
// Spawn child sharing only stderr
spawn('prg', [], { stdio: ['pipe', 'pipe', process.stderr] });
// Open an extra fd=4, to interact with programs presenting a
// startd-style interface.
spawn('prg', [], { stdio: ['pipe', null, null, null, 'pipe'] });
文档中的所有示例:https://nodejs.org/api/child_process.html#child_process_options_stdio