How to read child_process.spawnSync stdout with stdio option 'inherit'
Asked Answered
A

2

28
var childProcess = cp.spawnSync(command, args, {
    cwd: process.cwd(),
    env: process.env,
    stdio: 'inherit',
    encoding: 'utf-8'
});

childProcess.output always eq [null, null, null]

process.stdout.write hook doesn't give me any output

Adonic answered 28/2, 2016 at 22:26 Comment(2)
Have you found any solution to this? I have the same problem, I need to use 'inherit' in order to keep the progress display but I cannot hook stdout.write or listen for data event...Guttapercha
@FranDios My workaround is to use pipe to catch process output stdio: [0, isOutputNeeded ? 'pipe' : 1, 2],Adonic
C
26

If you don't use 'pipe' then childProcess.output will not contain the output.

var cp = require('child_process');

var command = 'echo';
var args = ['hello', 'world'];

var childProcess = cp.spawnSync(command, args, {
    cwd: process.cwd(),
    env: process.env,
    stdio: 'pipe',
    encoding: 'utf-8'
});

console.log(childProcess.output); // [ null, 'hello world\n', '' ]

This is sorta kinda indicated in the documentation for child.stdout and elsewhere, but it's not entirely unambiguous. (By all means, if you wish to see it improved, open a pull request against the Node.js repo.)

Cowen answered 29/2, 2016 at 0:48 Comment(3)
This way I will miss child_process progress displaying. It's important for me.Adonic
@nitro-n: see to my solution to get in-progress outputUraeus
Thanks for this. For others, you can get the output string with childProcess.output[1] #=> 'hello world\n'Countess
U
6

Use this for in-process displaying of progress:

var cp = require('child_process');

var command = 'echo';
var args = ['hello', 'world'];

var childProcess = cp.spawnSync(command, args, {
    cwd: process.cwd(),
    env: process.env,
    stdio: [process.stdin, process.stdout, process.stderr],
    encoding: 'utf-8'
});

So you replace string 'pipe' with the array [process.stdin, process.stdout, process.stderr].

Uraeus answered 9/10, 2018 at 10:11 Comment(4)
Please comment on down-vote. We are all here to learn and help learning, right?Uraeus
My guess is the downvote is due to the fact that this solution does not include a way to read the value of stdout. It does show how to inspect/display stdout, but I believe @Adonic was asking for a way to store stdout and display it (via stdio: 'inherit'). stdio: [process.stdin, process.stdout, process.stderr] is equivalent to stdio: 'inherit'. So, effectively, this solution is the same as the example in the original question.Koger
stdio: [process.stdin, process.stdout, process.stderr] is equivalent to the OP's stdio: 'inherit'.Bridesmaid
Voted up only because this discussion allowed to clarify what it was said by @BridesmaidFreed

© 2022 - 2024 — McMap. All rights reserved.