2

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?

Luka
  • 2,779
  • 3
  • 17
  • 32

1 Answers1

3

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

Please refer to this example: How to find a good/optimal dictionary for zlib 'setDictionary' when processing a given set of data?

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);
ZachB
  • 13,051
  • 4
  • 61
  • 89
Rabea
  • 1,938
  • 17
  • 26
  • Can you provide me a code example how to deflate with dictionary? – Luka Mar 10 '16 at 19:13
  • The link explains how to generate a dictionary and why, so i didnt see the reason for me to duplicate it here, and also there is an example to actually produce it, thats why i am using the same buffer from their example – Rabea Mar 10 '16 at 21:16