Search code examples
javascriptnode.jschild-processspawn

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.

// 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.


Solution

  • You can specify separate options for stdin, stdout and 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. 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.