25
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

nitro-n
  • 423
  • 1
  • 5
  • 9
  • 4
    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... – Fran Dios Jul 28 '16 at 02:09
  • @FranDios My workaround is to use pipe to catch process output `stdio: [0, isOutputNeeded ? 'pipe' : 1, 2],` – nitro-n Aug 04 '16 at 07:18

2 Answers2

24

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

Trott
  • 66,479
  • 23
  • 173
  • 212
5

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

mvermand
  • 5,829
  • 7
  • 48
  • 74
  • 5
    Please comment on down-vote. We are all here to learn and help learning, right? – mvermand Dec 20 '18 at 06:58
  • 8
    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 @nitro-n 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. – Matt Kahl Mar 15 '19 at 04:57
  • 4
    `stdio: [process.stdin, process.stdout, process.stderr]` is equivalent to the OP's `stdio: 'inherit'`. – Bluu Mar 17 '20 at 18:30
  • 1
    Voted up only because this discussion allowed to clarify what it was said by @Bluu – Eduardo Montoya Dec 11 '20 at 09:10