gpt4 book ai didi

node.js - 如何在不使用阻塞 stdio 的情况下从 node.js 中的子进程传输/流式传输大数据?

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

我在 node.js 中有一堆(子)进程需要传输大量数据。

当我阅读手册时,它说它们之间的 stdio 和 ipc 接口(interface)阻塞,所以不会这样做。

我正在研究使用文件描述符,但我找不到从它们流式传输的方法(请参阅我的另一个更具体的问题 How to stream to/from a file descriptor in node?)

我想我可能会使用网络套接字,但我担心这会产生不必要的开销。

我也看到了这个,但不一样(并且没有答案:How to send huge amounts of data from child process to parent process in a non-blocking way in Node.js?)

最佳答案

我找到了一个似乎可行的解决方案:在生成子进程时,您可以传递 stdio 的选项并设置管道来传输数据。

诀窍是添加一个附加元素,并将其设置为“管道”。

parent进程流到child.stdio[3]

var opts = {
stdio: [process.stdin, process.stdout, process.stderr, 'pipe']
};
var child = child_process.spawn('node', ['./child.js'], opts);

// send data
mySource.pipe(child.stdio[3]);

//read data
child.stdio[3].pipe(myHandler);

child 中打开文件描述符 3 的流。

// read from it
var readable = fs.createReadStream(null, {fd: 3});

// write to it
var writable = fs.createWriteStream(null, {fd: 3});

请注意,并非您从 npm 获得的每个流都能正常工作,我尝试了 JSONStream.stringify() 但它产生了错误,但在我通过 through2 管道传输后它工作了. (不知道为什么会这样)。

编辑:一些观察:似乎管道并不总是双工流,因此您可能需要两个管道。并且发生了一些奇怪的事情,在一种情况下,它只有在我也有一个 ipc channel 时才有效,所以总共 6 个:[stdin,stdout,stderr,pipe,pipe,ipc]。

关于node.js - 如何在不使用阻塞 stdio 的情况下从 node.js 中的子进程传输/流式传输大数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24582213/

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