NodeJS: How to compress string to Buffer or Base64 using Brotli
Want to use Promises? See this post on Promisifying brotliCompress
and brotliDecompress
.
Compression example
const zlib = require('zlib');
// Sample string to compress
const stringToCompress = "This is a sample string to be compressed using Brotli in Node.js";
// Convert the string to a Buffer
const bufferToCompress = Buffer.from(stringToCompress, 'utf-8');
// Compress the buffer using Brotli
zlib.brotliCompress(bufferToCompress, (err, compressedBuffer) => {
if (err) {
console.error('Error compressing the string:', err);
return;
}
console.log('Compressed Buffer:', compressedBuffer);
// Optional: Convert the compressed buffer to a Base64 string for display
const compressedString = compressedBuffer.toString('base64');
console.log('Compressed String (Base64):', compressedString);
});
Decompression example
// Assume compressedBuffer is the buffer you got from the previous example
zlib.brotliDecompress(compressedBuffer, (err, decompressedBuffer) => {
if (err) {
console.error('Error decompressing the string:', err);
return;
}
const decompressedString = decompressedBuffer.toString('utf-8');
console.log('Decompressed String:', decompressedString);
});