NodeJS: How to use brotliCompress/brotliDecompress with Promises

import { brotliCompress as _brotliCompress, brotliDecompress as _brotliDecompress } from "zlib";
import { promisify } from "util";

const brotliCompress = promisify(_brotliCompress);
const brotliDecompress = promisify(_brotliDecompress);

Usage example

import { brotliCompress as _brotliCompress, brotliDecompress as _brotliDecompress } from 'zlib';
import { promisify } from 'util';

// Promisify the Brotli compression and decompression functions
const brotliCompress = promisify(_brotliCompress);
const brotliDecompress = promisify(_brotliDecompress);

async function compressAndDecompress() {
  try {
    // 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
    const compressedBuffer = await brotliCompress(bufferToCompress);
    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);

    // Decompress the buffer using Brotli
    const decompressedBuffer = await brotliDecompress(compressedBuffer);
    const decompressedString = decompressedBuffer.toString('utf-8');
    console.log('Decompressed String:', decompressedString);
  } catch (err) {
    console.error('Error during compression/decompression:', err);
  }
}

// Call the function
compressAndDecompress();