1

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.

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

9 Comments

I tried this, but the problem here is for example the command I am running is asking for some inputs like: ``` Enter your name: <Then we should enter the name from terminal> Enter your age: <Then we should enter the age from terminal>``` In these cases, it's not showing the Enter your name and Enter your age because we are piping stdout.
Here I can use stdio: 'inherit', this, but I want to read the entire data in terminal, Is it possible to get the data that is in terminal after the command execution?
Yes, you are piping stdout so you need to write the data to the terminal yourself.
I have updated the answer with an exampe of how the handle the child stdout.
But this will not give the interactiveness with the terminal right? The same example I mentioned above Enter your name will be output to the terminal once the command execution is done but not in between the command execution.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.