W3Cschool
恭喜您成為首批注冊用戶
獲得88經(jīng)驗值獎勵
要創(chuàng)建我們自己的流,繼承流類,并實現(xiàn)下表中列出的幾個基本方法。
用例 | 類 | 實施方法 |
---|---|---|
只讀 | Readable | _read |
只寫 | Writable | _write |
讀寫 | Duplex | _read, _write |
操作被寫入數(shù)據(jù),然后讀出結(jié)果 | Transform | _transform, _flush |
我們可以繼承Readable類,在類中實現(xiàn)_read成員。
當(dāng)有人請求讀取數(shù)據(jù)時,流API調(diào)用該方法。
要傳遞數(shù)據(jù),調(diào)用繼承的成員函數(shù) push
傳入數(shù)據(jù)。
如果調(diào)用push(null),這表示讀取流的結(jié)束。
以下代碼顯示如何創(chuàng)建可讀流并返回1-10。
如果你運行這個,你會看到所有這些數(shù)字被打印。
var Readable = require("stream").Readable;
var util = require("util");
/* m.hgci.cn */
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);
從Writable類繼承并實現(xiàn)_write方法。
_write方法在需要處理作為其第一個參數(shù)的塊中傳遞。
以下代碼創(chuàng)建一個簡單的可寫流,將所有傳入的數(shù)據(jù)記錄到控制臺。
var Writable = require("stream").Writable;
var util = require("util");
/* m.hgci.cn */
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);
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網(wǎng)安備35020302033924號
違法和不良信息舉報電話:173-0602-2364|舉報郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: