ZSTD 解压缩前端处理方案(干货简单)

如果可以实现记得点赞分享,谢谢老铁~

1.需求描述

由于后台返回数据量大,请求资源比较耗时,需要一个方案来优化性能,下图是一个后台返回一个二进制的文件,需要解析成我们想要的对象
在这里插入图片描述

2.使用场景

采用ZSTD方案,官网链接:http://facebook.github.io/zstd/ (可能需要翻墙)

3.首先需要先安装包,命令:

npm install fzstd
or
yarn add fzstd

4.结合官网的例子,首先展示案例及说明
// I will assume that you use the following for the rest of this guide
import * as fzstd from 'fzstd';

// This is an ArrayBuffer of data
const compressedBuf = await fetch('/compressedData.zst').then(
  res => res.arrayBuffer()
);
if (fzstd) {
    
    
 //将ArrayBuffer转换成Uint8Array, zstd输入参数必须为Uint8Array类型
  const compressed = new Uint8Array(compressedBuf);
  // 解压缩成Uint8Array
  const decompressed = fzstd.decompress(compressed);
  // 将字符串转为JSON
  let result = new TextDecoder().decode(decompressed);
  result = JSON.parse(result);
}
5.由于我采用的是axios, 所以需要特殊处理一下

因为咱们是解析一个二进制的文件,所以需要进行指定返回类型
需要指定 responseType: “arraybuffer” 很重要!!!

export async function getCaseById(params: props): Promise<any> {
    
    
  return request("//getById", {
    
    
    method: "GET",
    data: params,
    responseType: "arraybuffer",
  });
}
6.然后再响应拦截器中获取,需要指定判断一下 :response?.config.responseType === “arraybuffer”
instance.interceptors.response.use(
  async function (response: any) {
    
    
    if (response?.config.responseType === "arraybuffer") {
    
    
      if (fzstd) {
    
    
        //将ArrayBuffer转换成Uint8Array, zstd输入参数必须为Uint8Array类型
        const compressed = new Uint8Array(response?.data);
        // 解压缩成Uint8Array
        const decompressed = fzstd.decompress(compressed);
        // 将字符串转为JSON
        const result = new TextDecoder().decode(decompressed);
        response.data = JSON.parse(result);
      }
    } else {
    
    
      if (!response?.data.data) {
    
    
        message.error(response?.data.message || "服务器异常,请稍后再试");
        return;
      }
    }

    return response?.data;
  },

收工!谢谢老铁们的点赞收藏~

猜你喜欢

转载自blog.csdn.net/Gas_station/article/details/131004029