Nodejs的child_process生成自定义的stdio

我想使用自定义stream来处理child_process.spawn stdio。

例如

const cp = require('child_process'); const process = require('process'); const stream = require('stream'); var customStream = new stream.Stream(); customStream.on('data', function (chunk) { console.log(chunk); }); cp.spawn('ls', [], { stdio: [null, customStream, process.stderr] }); 

我得到错误Incorrect value for stdio stream

有关于child_process.spawn的文档https://nodejs.org/api/child_process.html#child_process_options_stdio 。 它说stdio选项,它可以采取Stream对象

stream对象 – 将引用tty,文件,套接字或pipe道的可读或可写的stream与subprocess共享。

我想我错过了这个“指”部分。

它似乎是一个bug: https : customStream当它传递给spawn()时, customStream似乎还没有准备好。 您可以轻松地解决这个问题:

 const cp = require('child_process'); const stream = require('stream'); // use a Writable stream var customStream = new stream.Writable(); customStream._write = function (data) { console.log(data.toString()); }; // 'pipe' option will keep the original cp.stdout // 'inherit' will use the parent process stdio var child = cp.spawn('ls', [], { stdio: [null, 'pipe', 'inherit'] }); // pipe to your stream child.stdout.pipe(customStream);