1

Playing around with child_process and I want to pipe spawned cp output to custom stream.

I don't understand why in first case piping doesn't works and in second does.

Presets

const cp = require('child_process');
const process = require('process');
const stream = require('stream');

var writable = new stream.Writable();
writable._write = function (data) {
    console.log(data.toString());
};    

Doesn't work

var spawnedProcess = cp.spawn('ls', [], {
    stdio: [process.stdin, process.stdout, process.stderr] 
});
process.stdout.pipe(writable);

Outputs log into terminal but does't pipe it.

Does work

var spawnedProcess = cp.spawn('ls', [], {});
spawnedProcess.stdout.pipe(writable);

Pipes output to writable.

Mr Br
  • 3,831
  • 1
  • 20
  • 24

1 Answers1

1

The doc says process.stdout is only a Writable stream so you can't pipe from it. It's weird it doesn't throw an Error: Cannot pipe. Not readable. though. Also, cp.stdout is a Readable stream so it pipes as it should.

Shanoor
  • 13,344
  • 2
  • 29
  • 40
  • Understood. Bit off topic, if I would like to put custom stdout for spawn, it should be readable stream then? I'll be free to share my related question with you http://stackoverflow.com/questions/34967278/nodejs-child-process-spawn-custom-stdio – Mr Br Jan 26 '16 at 12:29
  • @MrBr Nope, when you pipe to a stream, that destination stream has to be Writable: `readable.pipe(writable);`. I answered your other question :) – Shanoor Jan 26 '16 at 12:51