【问题标题】:How to pipe from NodeJS to NodeJS?如何从 NodeJS 管道传输到 NodeJS?
【发布时间】:2020-04-01 02:53:02
【问题描述】:

我想做的是这样的:

node x.js | node y.js

文件 x.js 只是打印一个字符串:

console.log("hi");

文件 y.js 旨在通过process.stdin 获取字符串“hi”并对其进行处理。

但它不起作用。 zsh(我的 shell)抛出这个错误:zsh: command not found: node.

我做错了什么?

【问题讨论】:

  • 为我工作。 $ node hi.js | grep -rn "hi" 与输出 (standard input):1:hi。也许向我们展示您的y.js 文件?
  • 你真的安装了node吗?
  • 是的。节点已安装。只需调用node x.js 即可成功打印“hi”。
  • @KentShikama node hi.js | grep -rn "hi" 也适用于我。第二个文件中的内容似乎并不重要。如果它是空的,它就不起作用。如果它试图从process.stdin.on 获取标准输入,它不起作用...
  • 那里发生了什么很神秘

标签: node.js bash pipe stdout stdin


【解决方案1】:

第二个文件中的内容很重要。您需要从标准输入读取。请尝试以下操作。

$ cat hi.js 
console.log("hi");

$ cat read.js 
var readline = require('readline');
var rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  terminal: false
});

rl.on('line', function(line){
    console.log(line);
})

$ node hi.js | node read.js
hi

【讨论】:

  • 我试过了,但还是:zsh: command not found: node。我不明白为什么当我将某些东西传递给它时找不到节点。顺便说一下,我通过 brew (MacOS) 安装了节点。
猜你喜欢
  • 2016-06-14
  • 2012-12-30
  • 2015-05-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多