W3Cschool
恭喜您成為首批注冊(cè)用戶
獲得88經(jīng)驗(yàn)值獎(jiǎng)勵(lì)
要?jiǎng)?chuàng)建我們自己的流,繼承流類,并實(shí)現(xiàn)下表中列出的幾個(gè)基本方法。
用例 | 類 | 實(shí)施方法 |
---|---|---|
只讀 | Readable | _read |
只寫(xiě) | Writable | _write |
讀寫(xiě) | Duplex | _read, _write |
操作被寫(xiě)入數(shù)據(jù),然后讀出結(jié)果 | Transform | _transform, _flush |
我們可以繼承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.15014759268.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類繼承并實(shí)現(xiàn)_write方法。
_write方法在需要處理作為其第一個(gè)參數(shù)的塊中傳遞。
以下代碼創(chuàng)建一個(gè)簡(jiǎn)單的可寫(xiě)流,將所有傳入的數(shù)據(jù)記錄到控制臺(tái)。
var Writable = require("stream").Writable;
var util = require("util");
/* www.15014759268.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號(hào)-3|閩公網(wǎng)安備35020302033924號(hào)
違法和不良信息舉報(bào)電話:173-0602-2364|舉報(bào)郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號(hào)
聯(lián)系方式:
更多建議: