【发布时间】:2020-06-03 22:50:48
【问题描述】:
我正在尝试通过 node.js 将 unix 可执行文件作为外部应用程序运行:(Reference)
const execFile = require('child_process').execFile;
const executable = execFile('identifiers', ['--help'], [execPath], (error, stdout, stderr) => {
if (error) {
console.error('stderr', stderr);
throw error;
}
console.log('stdout', stdout);
});
程序 identifiers 应该使用参数 --help 执行,而不是失败并显示:
Uncaught Error: spawn identifiers ENOENT at Process.ChildProcess._handle.onexit (internal/child_process.js:264) at onErrorNT (internal/child_process.js:456) at processTicksAndRejections (internal/process/task_queues.js:80)
console.log(execPath) 在我的节点项目中打印正确的 identifiers 执行路径。
这实际上是返回根节点项目的目录,并以代码0退出:
var sys = require('sys'),
spawn = require('child_process').spawn,
ls = spawn('ls', ['-l']);
ls.stdout.on('data', function (data) {
console.log('stdout: ' + data);
});
ls.stderr.on('data', function (data) {
console.log('stderr: ' + data);
});
ls.on('exit', function (code) {
console.log('exit code ' + code);
});
- 为什么
execFile会抛出错误? - 如何在 NodeJS 中正确运行带 args 的可执行文件?
【问题讨论】:
-
为什么您的 execPath 在 options 参数的数组中?文档说它期待一个对象
-
感谢@innis 的提示,我在阅读文档时应该更加彻底
标签: javascript node.js exec child-process spawn