node.js - 使用 Node.js 从 'named pipe'/fifo 读取

标签 node.js linux bash macos named-pipes

我有这个:

  const p = path.resolve(projectRoot + '/NAMEDPIPEIN');
  const fd = fs.openSync(p, 'r+');

  fs.createReadStream(null, {fd}).on('data', function (d) {
    if (String(d).trim() === '[stdin end]') {
      return process.nextTick(cb);
    }
    process.argv.push(String(d).trim());
  });

我启动 Node.js 进程,然后写入命名管道。由于某种原因,数据回调中似乎没有数据到达。

我正在这样写命名管道:

 mkfifo NAMEDPIPEIN
 echo "foo bar baz" > NAMEDPIPEIN

最佳答案

另一个解决方案,来自@richardpringle应该可以,但功能有限。

如果您尝试以这种方式打开多个 FIFO(超过线程池中的线程数),您打开的第一个 FIFO 将不再是流数据。这是因为 fs 模块并非设计用于在非阻塞模式下使用文件描述符。相反,请使用 net 模块!

来自 https://stackoverflow.com/a/52622722/1843507当前从 FIFO 实现流式传输的方法是使用套接字:

const fs = require('fs');
const net = require('net');

fs.open('path/to/fifo/', fs.constants.O_RDONLY | fs.constants.O_NONBLOCK, (err, fd) => {
  // Handle err
  const pipe = new net.Socket({ fd });
  // Now `pipe` is a stream that can be used for reading from the FIFO.
  pipe.on('data', (data) => {
    // process data ...
  });
});

总之,你可以使用@richardpringle的解决方案,如果您正在运行脚本并且不介意占用线程池中的线程之一。否则,您绝对应该使用此解决方案。

关于node.js - 使用 Node.js 从 'named pipe'/fifo 读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44982499/

相关文章:

node.js - 使用 Mocha 时出现超时错误

c++ - 当进程通过 msgrcv 读取 IPC 消息时会发生什么?

Bash 列表理解或映射

linux - 在脚本中重定向 stderr 并添加前缀

bash - Windows 10 上的 Bash 和 Ubuntu 终端有什么区别

IE8 上的 Node.js HTTPS Hello world 服务器

javascript - 我应该在 Promise.all 中使用 await 吗?

javascript - Nodejs 中的输出选项

linux - .deb 包 conffiles 问题

c++ - 从另一个共享对象动态加载共享对象时的约束?