天天看點

Php解壓pako,使用pako.js解壓服務端傳來的gzip檔案(火币api)

在接入火币api的時候發現,火币websocket中傳輸的資料均已經gzip壓縮過,需要在用戶端解壓

這裡使用pako.js解壓,直接上代碼

####前端環境###

//需要先引入pako.js

socket.onmessage = function (msg) {

if (msg.data instanceof Blob){

blob = msg.data;

let result = '';

let reader = new FileReader();

reader.readAsBinaryString(blob);

reader.onload = function() {

result = JSON.parse(pako.inflate(reader.result,{to:'string'}));

//列印出傳回的資料

console.log(result);

}

}

}

由于傳過來的是檔案,需要用FileReader先讀取出來。readAsBinaryString,使讀出來的檔案傳回成BinaryString,再使用pako.inflate解壓,第二個參數{to:'string'},讓解壓後傳回字元串。

####Node環境####

//首先 npm install pako

var pako = require('pako');

connection.on('message', message => {

//這裡message列印出來為object,message.type=binary.

result = JSON.parse(pako.inflate(message.binaryData, {to:'string'}));

}

這裡隻是簡單的解壓,詳細的壓縮解壓請查詢文檔