首页 > 语言 > JavaScript > 正文

node.js使用stream模块实现自定义流示例

2024-05-06 15:44:25
字体:
来源:转载
供稿:网友

本文实例讲述了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());            
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选