oput前端數(shù)據(jù)零存整取工具庫(kù)
oput 是一個(gè)用于前端讀取預(yù)定長(zhǎng)度數(shù)據(jù)的工具庫(kù),相當(dāng)于零存整取(0 put do)
- 零存代表,異步獲取到的數(shù)據(jù)是零碎的,且長(zhǎng)度不確定(例如tcp流的數(shù)據(jù))
- 整取代表,需要讀取的數(shù)據(jù)的長(zhǎng)度是確定的。
比如有一個(gè)場(chǎng)景,每次采集到的數(shù)據(jù)是128個(gè)字節(jié),但是我需要湊滿480個(gè)字節(jié)使用,那么就需要做緩存,生產(chǎn)和消費(fèi),更新緩存。
oput將這種行為封裝起來,減少重復(fù)編寫類似的代碼。
具體使用方式:
生產(chǎn)者:
通過write方法填充數(shù)據(jù),接收TypedArray和ArrayBuffer類型的數(shù)據(jù)
import OPut from 'oput'
const oput = new OPut(reader)
oput.write(new Uint32Array([1,2,3]))
消費(fèi)者:
方式1、按字節(jié)讀取:
function *reader(){
let b = yield 5;//讀取5個(gè)字節(jié)
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個(gè)字節(jié)
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)
})
評(píng)論
圖片
表情
