简体   繁体   中英

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 .

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. Error: Cannot pipe. Not readable. though. Also, cp.stdout is a Readable stream so it pipes as it should.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM