简体   繁体   English

了解节点流的操作顺序

[英]Understanding Node Streams sequence of operations

I am learning about Node Streams using Stream-Adventure ( https://github.com/substack/stream-adventure ). 我正在学习使用Stream-Adventure( https://github.com/substack/stream-adventure )的Node Streams。 I'm having a hard time understanding the HTML-Stream Lesson. 我很难理解HTML流课程。

This is the challenge : 这是挑战:

Your program will get some html written to stdin. 您的程序将把一些html写入stdin。 Convert all the inner html to upper-case for elements with a class name of "loud". 将类名称为“ loud”的元素的所有内部html转换为大写。

You can use trumpet and through to solve this adventure. 您可以使用trumpetthrough解决这个冒险。

I found the solution 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)

I cannot seem to understand the program flow above. 我似乎无法理解上面的程序流程。

How do the last two lines modify the stream output, even though there is no reference/callbacks to use the above stream? 即使没有引用/回调使用上述流,后两行如何修改流输出?

The key is to think asynchronously. 关键是异步思考。 Think of process.stdin.pipe(tr).pipe(process.stdout) as 'take the input put it through tr, which we'll elaborate on later, and print to stdout'. process.stdin.pipe(tr).pipe(process.stdout)视为“将输入通过tr进行输入,稍后我们将对其进行详细说明,然后打印到stdout”。

Then below we fill out the logic and say exactly what tr will be doing to the input. 然后,在下面我们填写逻辑并确切地说出tr将对输入执行的操作。 There is only one tr object in this program. 该程序中只有一个tr对象。 And the stream object is defined in terms of it. stream对象是根据它定义的。 The code using stream at the bottom is manipulating the same tr being used to filter stdin and stdout . 底部使用stream的代码正在处理用于过滤stdinstdout的相同tr Remember the hint Now stream outputs all the inner html content at '.beep' and the data you write to stream will appear as the new inner html content. 请记住提示, 现在stream所有内部html内容输出到'.beep'并且您写入stream的数据将显示为新的内部html内容。 That's exactly what the last line is doing. 这正是最后一行所做的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM