node.js - Nodejs child_process 生成自定义 stdio

标签 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]
});

我收到错误 stdio 流的值不正确

有 child_process.spawn https://nodejs.org/api/child_process.html#child_process_options_stdio 的文档.它表示 stdio 选项可以采用 Stream 对象

Stream object - Share a readable or writable stream that refers to a tty, file, socket, or a pipe with the child process.

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

最佳答案

这似乎是一个错误:https://github.com/nodejs/node-v0.x-archive/issues/4030 customStream 在传递给 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);

关于node.js - Nodejs child_process 生成自定义 stdio,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34967278/

相关文章:

node.js - 函数内nodejs变量的范围

ffmpeg - 如何通过ffmpeg在源代码中将HLS流保存到本地磁盘?

php - 使用 stream_filter_* 在 PHP 中处理大型(超过 1 Gig)文件

python - 子进程中的父记录器

javascript - Node/请求错误: "Processing POST Request: No Content-Type"

javascript - 顺序运行 Q Promise

javascript - 在 NodeJS 中包含 Javascript 文件,如 PHP

java - 如何确定我的 OutputStream 内部缓冲

java - Hadoop 作业未在大数据集中运行并抛出子错误

java - firebase如何获得 child 的 child ?