2014-04-04 40 views
1

我正在學習使用流 - 冒險節點流(https://github.com/substack/stream-adventure)。 我很難理解HTML流課程。瞭解節點流操作序列

這是挑戰:

你的程序將獲得一些HTML編寫到標準輸入。對於類名爲「loud」的元素,將所有 內部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) 

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

即使沒有引用/回調使用上述流,最後兩行如何修改流輸出?

+0

我不熟悉它,但不會'tr'已經管理到process.stdin? – webduvet

+0

有一個[類似的問題](http://stackoverflow.com/questions/24103981/how-does-piping-a-stream-back-to-itself-work-with-trumpet),和[討論]( https://github.com/nodeschool/discussions/issues/346) –

回答

0

關鍵是要異步思考。將process.stdin.pipe(tr).pipe(process.stdout)想象爲「通過tr進行輸入,稍後我們將詳細介紹,然後打印到stdout」。

然後在下面我們填寫邏輯並確切地說tr將對輸入做什麼。該程序中只有一個tr對象。並且stream對象是根據它定義的。在底部使用stream的代碼操縱用於過濾stdinstdout的相同tr。 記住提示現在stream輸出所有的內部html內容'.beep'和您寫入stream的數據將顯示爲新的內部html內容。這正是最後一行所做的。