How to read child_process.spawnSync stdout with stdio option 'inherit'
13,725
Solution 1
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.)
Solution 2
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]
.
Related videos on Youtube
Author by
nitro-n
Updated on June 17, 2022Comments
-
nitro-n almost 2 years
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
-
Fran Dios almost 8 yearsHave 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 hookstdout.write
or listen fordata
event... -
nitro-n almost 8 years@FranDios My workaround is to use pipe to catch process output
stdio: [0, isOutputNeeded ? 'pipe' : 1, 2],
-
-
nitro-n about 8 yearsThis way I will miss child_process progress displaying. It's important for me.
-
mvermand over 5 years@nitro-n: see to my solution to get in-progress output
-
mvermand over 5 yearsPlease comment on down-vote. We are all here to learn and help learning, right?
-
Matt Kahl about 5 yearsMy 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 @nitro-n was asking for a way to store stdout and display it (viastdio: 'inherit'
).stdio: [process.stdin, process.stdout, process.stderr]
is equivalent tostdio: 'inherit'
. So, effectively, this solution is the same as the example in the original question. -
Bluu about 4 years
stdio: [process.stdin, process.stdout, process.stderr]
is equivalent to the OP'sstdio: 'inherit'
. -
Eduardo Montoya over 3 yearsVoted up only because this discussion allowed to clarify what it was said by @Bluu
-
Joshua Pinter over 2 yearsThanks for this. For others, you can get the output string with
childProcess.output[1] #=> 'hello world\n'