gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 23:26:03 26 4
gpt4 key购买 nike

我想使用自定义流来处理 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com