Javascript 电子反应从终端命令侦听标准输出

Javascript 电子反应从终端命令侦听标准输出,javascript,events,electron,node-streams,Javascript,Events,Electron,Node Streams,我正在编写一个electron应用程序,它需要从命令行执行一个长时间运行的进程,并实时监控输出,但我不确定如何实现这个目标 基本上,如果终端命令打印“Find me!”,那么我希望应用程序像处理某种事件一样处理它 到目前为止,我已经能够做到: 使用“spawn”从electron启动终端命令 使用“console.log”打印终端命令的输出 它似乎保持异步打印-这是出乎意料的,但很好 tsx:以下代码将打印终端命令的输出 import { ChildProcessWithoutNullStrea

我正在编写一个electron应用程序,它需要从命令行执行一个长时间运行的进程,并实时监控输出,但我不确定如何实现这个目标

基本上,如果终端命令打印“Find me!”,那么我希望应用程序像处理某种事件一样处理它

到目前为止,我已经能够做到:

  • 使用“spawn”从electron启动终端命令
  • 使用“console.log”打印终端命令的输出
  • 它似乎保持异步打印-这是出乎意料的,但很好
  • tsx:以下代码将打印终端命令的输出

    import { ChildProcessWithoutNullStreams } from 'child_process';
    
    const sendOutput = (output: ChildProcessWithoutNullStreams | string) =>
    {
      if (typeof output === 'string') {
          console.log(`${output}\n`);
      } else {
        output.stdout.on('data', (data) => {
          console.log(`${data.toString()}\n`);
        });
        output.stderr.on('data', (data) => {
          console.log(`${data.toString()}\n`);
        });
    }
    }
    
    export function helloWorldRepeat(){
    
      let dir = "/Users/les/projects/github/tutorial/les-app/cpp_program";
      let cmd = "helloWorldRepeat"
    
      let comm = dir+ "/"+cmd;
      let params = [""];
    
      return {
        command: `command: ${comm} ${params}`,
        process: spawn(comm, params)
      }
    
    export function main(){
      let c = helloWorldRepeat();
      sendOutput(c.process);
    }
    
    }
    

    谢谢

    您应该使用
    child\u process.spawn
    来运行该命令,您将监听来自
    stdout
    stderr
    的信号,它们是可读的流。当信号到达时,你的应用程序应该动作

    let subprocess=child\u process.spawn(
    '命令',//参见注释
    ['arg1','arg2']
    )
    subprocess.on('error',()=>subprocess=null)//无法启动进程
    subprocess.stdout.on('data',您的事件\u处理程序)
    subprocess.stderr.on('data',事件处理程序)
    subprocess.on('close',()=>subprocess=null)
    
    其中
    您的\u事件\u处理程序是,我相信这意味着它接受单个字符串参数,其返回被忽略

    您的Electron应用程序的其余部分希望在内容到达时得到通知——或者,正确的内容——但您不希望Electron应用程序的其余部分必须知道任何有关子进程或可读流的信息。因此,您可能应该将所有这些放在一个返回EventEmitter实例的函数中,然后
    您的\u EVENT\u处理程序
    会在看到它关心的内容时触发一个干净的事件,其余时间不做任何事


    注意:对于节点的
    路径上的shell内置和命令
    ,您可以只使用程序名,但我遇到过,因此我建议始终为您希望运行的命令提供绝对路径


    (该链接还包含一个例子,说明如何在等待命令终止的命令中包装命令,然后用所有的STDUT或STDER来解决)。

    我认为我们不需要看到C++代码,这个问题不应该被标记为C++,因为它涉及电子和外壳之间的交互,而不是C++和shell。