在hapijs中压缩缓冲区并发送给客户端

时间:2019-02-27 00:44:05

标签: gzip protocol-buffers content-type zlib hapijs

我有一个巨大的JSON对象。 (最多可以包含100个对象的数组) 它具有的最小大小约为8kb。最大可以达到2 mb。

如果我使用response.type("application/json")作为JSON发送,则其大小为 8kb ;

response.type("application/json");
response.content = getJSONData();

为解决此问题,我使用protobufjs创建了一个缓冲区。 如果我使用protobufjs对其进行编码,并以octet-stream的形式发送,则其大小为 93kb

response.type("application/octet-stream");
response.content = myProtoBufSchema.encode(content).finish();

响应为字符串形式{"type":"Buffer","data":[10,36,51,48,53....]

如果我在上面的代码中添加response.variety = "buffer";,它将作为缓冲区对象发送,并使用以下内容在客户端进行转换,大小减小为 27kb

var buffer = new Uint8Array(xhr.response);
var response = parseProtobuf(buffer);

content-encoding: gzip仅在我作为JSON发送时可用。

但是当我将其作为缓冲区发送时并没有添加。

如果我添加response.header("Content-Encoding", "gzip");的大小减小为 600Bytes ,但是在浏览器err_content_decoding_failed上出现错误,因为它实际上并未压缩,但标头表示内容-编码为gzip。

还有什么我可以更改的,或者我如何在hapi中使用zlib来压缩缓冲区(不是JSON)。

0 个答案:

没有答案