在 node.js 中使用 zlib 使用字典压缩数据

Compression of data with dictionary using zlib in node.js

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

var d = zlib.deflateSync(s);

我在documentation under Class Options中注意到我可以设置字典,但我不知道如何使用它。

如何用字典压缩字符串?

对于 Nodejs 中的用法,您需要传递 class 缓冲区的实例作为您希望 zlib 与之比较的数据的字典。

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');
    }
  }

请参考这个例子: How to find a good/optimal dictionary for zlib 'setDictionary' when processing a given set of data?

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

 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);