【问题标题】:How to get the output of command executed using child_process in nodejs?如何在nodejs中使用child_process执行命令的输出?
【发布时间】:2021-09-08 14:57:21
【问题描述】:

我是 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',
    });

两者都可以吗?请帮我解决这个问题?

提前致谢。

【问题讨论】:

    标签: javascript node.js child-process spawn


    【解决方案1】:

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

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

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

    // 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 时才能正常工作。

    【讨论】:

    • 我试过这个,但这里的问题是,例如我正在运行的命令要求输入一些输入,例如: ``` 输入您的姓名: 输入您的年龄:```在这些情况下,它不会显示Enter your name and Enter your age ,因为我们正在管道标准输出。
    • 这里我可以用stdio: 'inherit',这个,但是我想在终端中读取整个数据,是否可以在命令执行后获取终端中的数据?
    • 是的,您正在管道标准输出,因此您需要自己将数据写入终端。
    • 我已经更新了答案,并举例说明了如何处理子标准输出。
    • 但这不会提供与终端的交互性吧?我上面提到的相同示例Enter your name 将在命令执行完成后输出到终端,但不会在命令执行之间。