【问题标题】:How do I spawn two processes from Node.js and pipe them together?如何从 Node.js 生成两个进程并将它们通过管道连接在一起?
【发布时间】:2023-01-12 21:17:08
【问题描述】:

我希望能够生成两个 Node.js 子进程,但将一个子进程的 stdout 通过管道传输到另一个子进程的 stdin。相当于:

curl "https://someurl.com" | jq .

My Node 的标准输出将转到终端或文件,具体取决于用户是否通过管道输出。

【问题讨论】:

    标签: node.js spawn


    【解决方案1】:

    您可以使用 Node.js 的 child_process 内置模块生成子进程。我们需要处理,所以我们会调用它两次:

    const cp = require('child_process')
    const curl = cp.spawn('curl', ['https://someurl.com'], { stdio: ['inherit', 'pipe', 'inherit'] })
    const jq = cp.spawn('jq', ['.'], { stdio: ['pipe', 'inherit', 'pipe'] })
    

    第一个参数是要运行的可执行文件,第二个是传递给它的参数数组,第三个是选项.我们需要告诉它进程的 stdin、stdout 和 stderr 将被路由到哪里:'inherit' 表示“使用主机 Node.js 应用程序的 stdio”,而 'pipe' 表示“我们将处理它”以编程方式。

    因此,在这种情况下,curl 的输出和 jq 的输入留待以编程方式处理,我们使用额外的代码行来处理:

    curl.stdout.pipe(jq.stdin)
    

    这意味着“将 curl 的标准输出插入 jq 的标准输入”。

    就这么简单。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-18
      • 2019-01-07
      • 1970-01-01
      • 2010-09-22
      • 2018-05-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多