oput前端数据零存整取工具库
oput 是一个用于前端读取预定长度数据的工具库,相当于零存整取(0 put do)
- 零存代表,异步获取到的数据是零碎的,且长度不确定(例如tcp流的数据)
 - 整取代表,需要读取的数据的长度是确定的。
 
比如有一个场景,每次采集到的数据是128个字节,但是我需要凑满480个字节使用,那么就需要做缓存,生产和消费,更新缓存。
oput将这种行为封装起来,减少重复编写类似的代码。
具体使用方式:
生产者:
通过write方法填充数据,接收TypedArray和ArrayBuffer类型的数据
import OPut from 'oput'
const oput = new OPut(reader)
oput.write(new Uint32Array([1,2,3])) 
消费者:
方式1、按字节读取:
function *reader(){
  let b = yield 5;//读取5个字节
  console.log(b[0])
} 
方式2、用TypedArray作为容器读取
function *reader(){
  let b = new Uint8Array(5);
  yield b;//填充到b中
  console.log(b[0])
  b = new Uint32Array(5);
  yield b;//填充到b中,又读取了20个字节
  console.log(b[0])
} 
方式3、read方法异步读取
  const oput = new OPut();
  oput.write(new Uint32Array([1, 2]));
  oput.write(new Uint32Array([1, 2]));
  oput.read(1).then(value=>{
    expect(value[0]).toBe(1)
    return oput.read(4)
  }).then(value=>{
    expect(value[3]).toBe(2)
  }) 
评论
