繁体   English   中英

如何获取在nodejs中使用child_process执行的命令的输出?

[英]How to get the output of command executed using child_process in nodejs?

我是 node js 的新手,我想在 node js 中执行一个命令,并希望将命令的运行状态显示到终端以及一些日志文件中。

// Displaying the output in terminal but I am not able to access child.stdout
const child = spawn(command,[], {
      shell: true,
      cwd: process.cwd(),
      env: process.env,
      stdio: 'inherit',
      encoding: 'utf-8',
    });

// Pushing the output to file but not able to do live interaction with terminal
const child = spawn(command,[], {
      shell: true,
      cwd: process.cwd(),
      env: process.env,
      stdio: 'pipe',
      encoding: 'utf-8',
    });

两者都可以吗? 请在这件事上给予我帮助?

提前致谢。

您可以为 stdin、stdout 和 stderr 指定单独的选项:

const child = spawn(command,[], {
      shell: true,
      cwd: process.cwd(),
      env: process.env,
      stdio: ['inherit', 'pipe', 'pipe'],
      encoding: 'utf-8',
    });

这样子进程继承了标准输入,你应该能够与它进行交互。 子进程使用 stdout(和 stderr)管道,您可以将输出写入文件。 由于子进程没有将输出发送到终端,因此您需要自己将输出写入终端。 这可以通过管道轻松完成:

// Pipe child stdout to process stdout (terminal)...
child.stdout.pipe(process.stdout);

// ...and do something else with the data.
child.stdout.on('data', (data) => ...);

这可能只有在子进程是一个简单的命令行程序并且没有基于文本的高级 UI 时才能正常工作。

暂无
暂无

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

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