從前面兩篇文章,我們了解到。想要把 Readable 的數(shù)據(jù)寫到 Writable,就必須先手動的將數(shù)據(jù)讀入內(nèi)存,然后寫入 Writable。換句話說,每次傳遞數(shù)據(jù)時,都需要寫如下的模板代碼
為了方便使用,Node.js 提供了 pipe() 方法,讓我們可以優(yōu)雅的傳遞數(shù)據(jù)
現(xiàn)在,就讓我們來看看它是如何實現(xiàn)的吧
pipe
首先需要先調(diào)用 Readable 的 pipe() 方法
執(zhí)行 pipe() 函數(shù)時,首先將 Writable 記錄到 state.pipes 中,然后綁定相關事件,最后如果 Readable 不是 flow 模式,就調(diào)用 resume() 將 Readable 改為 flow 模式
傳遞數(shù)據(jù)
Readable 從數(shù)據(jù)源獲取到數(shù)據(jù)后,觸發(fā) data 事件,執(zhí)行 ondata()
ondata() 相關代碼:
在 ondata(chunk) 函數(shù)內(nèi),通過 dest.write(chunk) 將數(shù)據(jù)寫入 Writable
此時,在 _write() 內(nèi)部可能會調(diào)用 src.push(chunk) 或使其 unpipe,這會導致 awaitDrain 多次增加,不能清零,Readable 卡住
當不能再向 Writable 寫入數(shù)據(jù)時,Readable 會進入 pause 模式,直到所有的 drain 事件觸發(fā)
觸發(fā) drain 事件,執(zhí)行 ondrain()
每個 drain 事件觸發(fā)時,都會減少 awaitDrain,直到 awaitDrain 為 0。此時,調(diào)用 flow(src),使 Readable 進入 flow 模式
到這里,整個數(shù)據(jù)傳遞循環(huán)已經(jīng)建立,數(shù)據(jù)會順著循環(huán)源源不斷的流入 Writable,直到所有數(shù)據(jù)寫入完成
unpipe
不管寫入過程中是否出現(xiàn)錯誤,最后都會執(zhí)行 unpipe()
Readable.prototype.unpipe() 函數(shù)會根據(jù) state.pipes 屬性和 dest 參數(shù),選擇執(zhí)行策略。最后會觸發(fā) dest 的 unpipe 事件
unpipe 事件觸發(fā)后,調(diào)用 onunpipe(),清理相關數(shù)據(jù)
End
在整個 pipe 的過程中,Readable 是主動方 ( 負責整個 pipe 過程:包括數(shù)據(jù)傳遞、unpipe 與異常處理 ),Writable 是被動方 ( 只需要觸發(fā) drain 事件 )
總結一下 pipe 的過程:
首先執(zhí)行 readbable.pipe(writable),將 readable 與 writable 對接上
當 readable 中有數(shù)據(jù)時,readable.emit('data'),將數(shù)據(jù)寫入 writable
如果 writable.write(chunk) 返回 false,則進入 pause 模式,等待 drain 事件觸發(fā)
drain 事件全部觸發(fā)后,再次進入 flow 模式,寫入數(shù)據(jù)
不管數(shù)據(jù)寫入完成或發(fā)生中斷,最后都會調(diào)用 unpipe()
unpipe() 調(diào)用 Readable.prototype.unpipe(),觸發(fā) dest 的 unpipe 事件,清理相關數(shù)據(jù)
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識,若有侵權等問題請及時與本網(wǎng)聯(lián)系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com