zlib
Created: 2016-06-15 11:13:46 -0700 Modified: 2016-06-15 16:03:32 -0700
Basics + example (reference)
Section titled Basics + example (reference)This is used for compression.
Note: zlib does work in the browser if you’re using webpack.
It’s pretty straightforward, so I’m just going to include an example of compressing and decompressing using gzip with no special options:
‘use strict’;
const zlib = require(‘zlib’);
const data = ‘something to compress’;
// If you want this to be synchronous, they provide synchronous functions (gzipSync and gunzipSync)
const compressed = zlib.gzip(data, (error, compressedData) => {
if (error) {
throw error;
}
// If saving in the database, use the “blob” format and just save the buffer
// directly. Otherwise, you could use “text” and save base64.
console.log(compressedData.toString(‘base64’));
console.log(‘base64 size: ’ + compressedData.toString(‘base64’).length);
console.log(‘byteLength of compressed data: ’ + compressedData.byteLength);
zlib.gunzip(compressedData, (error, uncompressedData) => {
if (error) {
throw error;
}
console.log(uncompressedData.toString());
});
});