node.js - 如何将流传输到 Node 中的文件描述符?

标签 node.js posix file-descriptor

我正在 Node 中编写一个 cli,我想打开用户 $EDITOR 来编辑从流中读取的数据(http 响应 IncomingMessage)。

如何将数据发送到文件描述符?

在 bash 中我可以这样写:

$EDITOR <(curl $url)

$DIFF <(curl $url_1) <(curl $url_2)

<(curl $url)扩展为类似 /proc/self/fd/11

echo <(curl $url)
/proc/self/fd/11

但是我该如何用 JavaScript 编写它呢?

import cp from 'child_process'
const fisrt = request(...);
const second = require(...);
const first_fd = ???;
const second_fd = ???;

const proc = cp.spawn(process.env.DIFF, [first_fd, second_fd] { stdio: 'inherit' });

好的,如果stream由套接字或 fd 支持,您可以将其传递给 options.stdio ,但如果不是,如果它是转换流怎么办?

options.stdio object - Share a readable or writable stream that refers to a tty, file, socket, or a pipe with the child process. The stream's underlying file descriptor is duplicated in the child process to the fd that corresponds to the index in the stdio array. The stream must have an underlying descriptor (file streams do not until the 'open' event has occurred).

是的,我可以创建一个临时文件,但我可以在没有临时文件的情况下完成它吗?

最佳答案

您可以使用以下 nodejs 代码将下载的内容流式传输到终端中的 vim 文本编辑器中:

const { spawn } = require('child_process');
const request = require('request');
// 
request({
    url: 'https://google.com' 
}, function (err, res, body) { 
    const vi = spawn('vi', ['-'], { stdio: ['pipe', process.stdout, process.stderr] });

    vi.stdin.write(body);
    vi.stdin.end();
});

然后,如果您从终端执行此代码,它将下载 google 的 html 并让您编辑并将其保存在文件中。您可以使用 :w myfile.txt 在 vi​​m 中保存到文件。

有关此事的进一步阅读:https://2ality.com/2018/05/child-process-streams.html

关于node.js - 如何将流传输到 Node 中的文件描述符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56928613/

相关文章:

node.js - 将此消息发送到您的机器人时出错 : HTTP status code NotFound

node.js - 如何将 0x(用于 Node.js 分析)与 TS-Node 结合使用?

css - 在 Jade 中使用背景图像

c - 执行后维护pthread

c - 调用免费电话前是否需要重置保护

bash - 将具有特定名称的目录递归复制到维护结构的新位置

java - 将 Java 套接字文件描述符传递给 C 二进制文件的最有效方法

c - fopen和open有什么关系?

c - 无法打开文件 C

javascript - 如何在 Linux 中使用 WebRTC 制作命令行应用程序?