如何从NodeJS传递到NodeJS?

问题描述 投票:0回答:1

我想做的是这样的:

node x.js | node y.js

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

console.log("hi");

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

但是它不起作用。 zsh(我的外壳)抛出此错误:zsh: command not found: node

我在做什么错?

node.js bash pipe stdout stdin
1个回答
0
投票

第二个文件中的内容并不重要。您需要阅读stdin。请尝试以下操作。

$ 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
© www.soinside.com 2019 - 2024. All rights reserved.