简体   繁体   English

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

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

I am new to node js, I want to execute a command in node js and want to display the running status of the command to the terminal and also to some log file.我是 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',
    });

Is it possible to do both?两者都可以吗? Please help me with this?请在这件事上给予我帮助?

Thanks in advance.提前致谢。

You can specify separate options for stdin, stdout and stderr:您可以为 stdin、stdout 和 stderr 指定单独的选项:

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

This way the subprocess inherits stdin and you should be able to interact with it.这样子进程继承了标准输入,你应该能够与它进行交互。 The subprocess uses pipes for stdout (and stderr) and you can write the output to a file.子进程使用 stdout(和 stderr)管道,您可以将输出写入文件。 Because output is not sent to the terminal by the subprocess, you need to write the output to the terminal yourself.由于子进程没有将输出发送到终端,因此您需要自己将输出写入终端。 This can easily be done by piping:这可以通过管道轻松完成:

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

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

This probably only works correctly if the subprocess is a simple command line program and does not have an advanced text-based UI.这可能只有在子进程是一个简单的命令行程序并且没有基于文本的高级 UI 时才能正常工作。

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

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