Mr Br
Mr Br

Reputation: 3901

Nodejs - difference between spawn.stdout and process.stdout

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.

Upvotes: 1

Views: 715

Answers (1)

Shanoor
Shanoor

Reputation: 13692

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.

Upvotes: 1

Related Questions