Node.js的子进程 spawn 自定义 stdio

12
我想使用自定义流来处理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 对象 - 共享一个可读或可写流,该流与子进程引用终端、文件、套接字或管道。

我想我可能缺少了这个“与子进程引用”的部分。

1个回答

12

这似乎是一个bug: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);

是的,这是我正在使用的东西。谢谢。 - Mr Br
1
虽然这是一个不错的解决方法,但实际问题在于stdio流需要一个底层文件描述符。自定义流没有这个。 - Jelle De Loecker

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接