Node.js 自定義流

2018-02-16 19:15 更新

要?jiǎng)?chuàng)建我們自己的流,繼承流類,并實(shí)現(xiàn)下表中列出的幾個(gè)基本方法。

用例實(shí)施方法
只讀Readable_read
只寫Writable_write
讀寫Duplex_read, _write
操作被寫入數(shù)據(jù),然后讀出結(jié)果Transform_transform, _flush

創(chuàng)建可讀流

我們可以繼承Readable類,在類中實(shí)現(xiàn)_read成員。

當(dāng)有人請(qǐng)求讀取數(shù)據(jù)時(shí),流API調(diào)用該方法。

要傳遞數(shù)據(jù),調(diào)用繼承的成員函數(shù) push 傳入數(shù)據(jù)。

如果調(diào)用push(null),這表示讀取流的結(jié)束。

以下代碼顯示如何創(chuàng)建可讀流并返回1-10。

如果你運(yùn)行這個(gè),你會(huì)看到所有這些數(shù)字被打印。

var Readable = require("stream").Readable; 
var util = require("util"); 
/* www.o2fo.com */
function Counter() { 
    Readable.call(this); 
    this._max = 10; 
    this._index = 1; 
} 
util.inherits(Counter, Readable); 

Counter.prototype._read = function () { 
    var i = this._index++; 
    if (i > this._max)
        this.push(null);
    else { 
        var str = " " + i; 
        this.push(str);
    } 
}; 
// Usage, same as any other readable stream 
var counter = new Counter(); 
counter.pipe(process.stdout); 

創(chuàng)建可寫流

從Writable類繼承并實(shí)現(xiàn)_write方法。

_write方法在需要處理作為其第一個(gè)參數(shù)的塊中傳遞。

以下代碼創(chuàng)建一個(gè)簡(jiǎn)單的可寫流,將所有傳入的數(shù)據(jù)記錄到控制臺(tái)。

var Writable = require("stream").Writable; 
var util = require("util"); 
/* www.o2fo.com */
function Logger() {
     Writable.call(this); 
} 
util.inherits(Logger, Writable); 

Logger.prototype._write = function (chunk) {
     console.log(chunk.toString()); 
}; 

// Usage, same as any other Writable stream 
var logger = new Logger(); 

var readStream = require("fs").createReadStream("log.txt"); 
readStream.pipe(logger); 


以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)