Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compression of data with dictionary using zlib in node.js

Tags:

node.js

zlib

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?

like image 918
Luka Avatar asked Mar 17 '26 15:03

Luka


1 Answers

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);
like image 100
Rabea Avatar answered Mar 20 '26 06:03

Rabea



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!