了解Node Streams操作序列

时间:2014-04-04 14:37:11

标签: javascript node.js stream

我正在使用Stream-Adventure(https://github.com/substack/stream-adventure)了解Node Streams。 我很难理解HTML-Stream课程。

这是挑战:

  

你的程序会得到一些写入stdin的html。转换所有   内部html为大写的,类名为"响亮"。

     

您可以使用trumpetthrough来解决此冒险。

我找到了解决方案here

var trumpet = require('trumpet');
var through = require('through');
var to_upper = function (buffer) {
  this.queue(buffer.toString().toUpperCase())
};
var tr = trumpet();

// Here I expect the output to stdout to have printed as is.
process.stdin.pipe(tr).pipe(process.stdout);

// In the below lines, there is no reference to the above stream 
// which should have already started to send to stdout.
// How are the lines below modifying the above stream?
var stream = tr.select('.loud').createStream()
stream.pipe(through(to_upper)).pipe(stream)

我似乎无法理解上面的程序流程。

最后两行如何修改流输出,即使没有引用/回调来使用上述流?

1 个答案:

答案 0 :(得分:0)

关键是要异步思考。将process.stdin.pipe(tr).pipe(process.stdout)视为'将输入通过tr,我们稍后会详细说明,然后打印到标准输出。

然后在下面我们填写逻辑并确切地说明tr将对输入做什么。此程序中只有一个tr对象。 stream对象是根据它定义的。底部使用stream的代码正在操纵用于过滤trstdin的{​​{1}}。 请记住提示 Now stdout输出stream处的所有内部html内容,并且您写入'.beep'的数据将显示为新的内部html内容。那&# 39;正是最后一行正在做的事情。