Nodejs child_process产生自定义stdio

时间:2016-01-23 18:41:00

标签: node.js stream child-process

我想使用自定义流来处理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,文件,套接字或管道的可读或可写流。

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

1 个答案:

答案 0 :(得分:7)

这似乎是一个错误:https://github.com/nodejs/node-v0.x-archive/issues/4030customStream传递给spawn()时似乎没有准备好。您可以轻松解决此问题:

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