在 node.js 中使用 zlib 使用字典压缩数据 [英] Compression of data with dictionary using zlib in node.js

查看:50
本文介绍了在 node.js 中使用 zlib 使用字典压缩数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我想压缩字符串 s 我可以做

If I want to deflate string s I can do

var d = zlib.deflateSync(s);

我在文档下的类选项中注意到我可以设置字典,但我不知道怎么用.

I noticed in the documentation under Class Options that I can set dictionary, but I don't know how to use it.

如何用字典压缩字符串?

How to deflate a string with dictionary?

推荐答案

对于在 Nodejs 中的使用,您需要传递一个 Buffer 类的实例作为您希望 zlib 与之进行比较的数据的字典.

For the usage in Nodejs you will need to pass an instance of class Buffer as a dictionary of the data you want zlib to compare with.

https://github.com/nodejs/node/blob/master/lib/zlib.js#L347

  if (opts.dictionary) {
    if (!(opts.dictionary instanceof Buffer)) {
      throw new Error('Invalid dictionary: it should be a Buffer instance');
    }
  }

请参考这个例子:如何找到好的/处理给定数据集时 zlib 'setDictionary' 的最佳字典?

根据此,您可以执行以下操作:

Depending on that, you can do the following:

 var zlib = require('zlib');
 var input = 'The dictionary should consist of strings (byte sequences) that are likely to be encountered later in the data to be      compressed, with the most commonly used strings preferably put towards the end of the dictionary. Using a dictionary is most useful when the data to    be compressed is short and can be predicted with good accuracy; the data can then be compressed better than with the default empty dictionary.';
 var dictionary = Buffer.from('rdsusedusefulwhencanismostofstringscompresseddatatowithdictionarybethe', 'utf8');
 var result = zlib.deflateSync(input, {dictionary: dictionary});
 console.log(result);

这篇关于在 node.js 中使用 zlib 使用字典压缩数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆