简体   繁体   English

在 NodeJS 中捕获 child_process 的 *complete* output stream

[英]Capturing the *complete* output stream of a child_process in NodeJS

I've been trying to capture the output of a child_process for a while now.我一直在尝试捕获 child_process 的 output 一段时间。 The following code example is my current attempt.以下代码示例是我当前的尝试。

Code:代码:

// Spawning a shell
var terminal = require('child_process').spawn(`sh`, [], { stdio: [ 'inherit', 'pipe', 'inherit'] });
console.log("Shell spawned!");

terminal.stdout.on('data', (data) => {
  console.log(`Received chunk ${data}`);
});

Output: Output:

Shell spawned! Shell 诞生!

Expected output:预期 output:

Shell spawned! Shell 诞生!

$ $

When using 'inherit' instead of 'pipe' on the stdout option, I get the expected output.在标准输出选项上使用“继承”而不是“管道”时,我得到了预期的 output。 But since I need to capture the output of the process/shell, 'inherit' has no use to me.但是由于我需要捕获进程/shell的output,所以'继承'对我没有用。 My question now is, how can I capture the whole output of the process's stdout stream and what is 'inherit' exactly doing?我现在的问题是,如何捕获进程的标准输出 stream 的整个 output 以及“继承”到底在做什么? I tried to capture the process.stdout after using 'inherit'- obviously with no luck.在使用“继承”后,我尝试捕获 process.stdout - 显然没有运气。

It is not possible to show the prompt from a child process shell because bash (and I assume other shells) don't output the prompt to stdout.无法从子进程 shell 显示提示,因为 bash (我假设其他外壳)不会 output 提示到 stdout。 See this post for details.有关详细信息,请参阅此帖子

You can simulate it by writing to standard out instead of console.log().您可以通过写入标准输出而不是 console.log() 来模拟它。

const term = require('child_process')
  .spawn('sh', [], { stdio: [ 'inherit', 'pipe', 'pipe'] });

process.stdout.write('$ ');

term.stdout.on('data', (data) => {
  process.stdout.write(`\n${data}$ `);
});

term.stderr.on('data', (data) => {
  process.stderr.write(`\n${data}$ `);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM