Node.js child_process生成自定义stdio [英] Nodejs child_process spawn custom stdio
问题描述
我想使用自定义流来处理child_process.spawn stdio。
I would like to use custom stream to handle 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]
});
我收到错误 stdio流的值不正确
。
有有关child_process.spawn的文档 https://nodejs.org/api/child_process.html#child_process_options_stdio 。它表示,对于stdio选项,它可以使用Stream对象
There is documentation for child_process.spawn https://nodejs.org/api/child_process.html#child_process_options_stdio. It says for stdio options that it can take Stream object
Stream对象-共享引用tty,文件,套接字或带有子进程的管道。
Stream object - Share a readable or writable stream that refers to a tty, file, socket, or a pipe with the child process.
我想我错过了这个指代部分。
I guess I'am missing this "refers to" part.
推荐答案
似乎是一个错误: https://github.com/nodejs/node-v0.x-archive/issues/4030 customStream
传递给spawn()时似乎还没有准备好。您可以轻松解决此问题:
It seems to be a bug: https://github.com/nodejs/node-v0.x-archive/issues/4030 The customStream
seems to be not ready when it's passed to spawn(). You can go around this issue easily:
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);
这篇关于Node.js child_process生成自定义stdio的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!