本文實例講述了node.js使用stream模塊實現自定義流。分享給大家供大家參考,具體如下:
有些時候我們需要自定義一些流,來操作特殊對象,node.js中為我們提供了一些基本流類。
我們新創建的流類需要繼承四個基本流類之一(stream.Writeable,stream.Readable,stream.Duplex,stream.Transform),并確保調用了父類構造函數。
一、實現自定義的可讀流
實現可讀流需繼承 stream.Readable,并實現 readable._read() 方法。
下面的代碼我們實現了一個從數組中讀取數據的流
const {Readable} = require('stream');//這里我們自定義了一個用來讀取數組的流class ArrRead extends Readable { constructor(arr, opt) { //注意這里,需調用父類的構造函數 super(opt); this.arr = arr; this.index = 0; } //實現 _read() 方法 _read(size) { //如果當前下標等于數組長度,說明數據已經讀完 if (this.index == this.arr.length) { this.push(null); } else { this.arr.slice(this.index, this.index + size).forEach((value) => { this.push(value.toString()); }); this.index += size; } }}let arr = new ArrRead([1, 2, 3, 4, 5, 6, 7, 8, 9, 0], { highWaterMark: 2});//這樣當我們監聽 'data' 事件時,流會調用我們實現的 _read() 方法往緩沖區中讀取數據//然后提供給消費者arr.on('data', function (data) { console.log(data.toString());});二、實現自定義的可寫流
實現可寫流必須繼承 stream.Writeable ,并實現 writeable._write() 方法。writable._writev() 方法是可選的。
const {Writable} = require('stream');//這里我們自定義了一個用來寫入數組的流class ArrWrite extends Writable { constructor(arr, opt) { super(opt); this.arr = arr; } //實現 _write() 方法 _write(chunk, encoding, callback) { this.arr.push(chunk.toString()); callback(); }}let data = [];let arr = new ArrWrite(data, { highWaterMark: 3});arr.write('1');arr.write('2');arr.write('3');console.log(data);三、實現自定義的可讀可寫流
可讀可寫流必須繼承 stream.Duplex,并實現 readable._read() 和 writable._write() 方法。
const {Duplex} = require('stream');//這里我們自定義了一個用來寫讀可寫數組的流class ArrReadWrite extends Duplex { constructor(arr, opt) { super(opt); this.arr = arr; this.index = 0; } //實現 _write() 方法 _write(chunk, encoding, callback) { this.arr.push(chunk.toString()); callback(); } //實現 _read() 方法 _read(size) { //如果當前下標等于數組長度,說明數據已經讀完 if (this.index == this.arr.length) { this.push(null); } else { this.arr.slice(this.index, this.index + size).forEach((value) => { this.push(value.toString()); }); this.index += size; } }}let data = [];let arrWR = new ArrReadWrite(data, { highWaterMark: 3});//往流中寫入數據arrWR.write('1');arrWR.write('2');arrWR.write('3');console.log(data);//往流中讀取數據console.log(arrWR.read(2).toString());console.log(arrWR.read(2).toString());
新聞熱點
疑難解答
圖片精選