Sample code for 30+ languages & platforms
React Native

Compress and Decompress a String

See more Compression Examples

Demonstrates how to compress and decompress a string.

Chilkat React Native Downloads

React Native
import { Compression, StringBuilder } from '@chilkat/react-native'

async function chilkatExample() {
  // This example assumes the Chilkat API to have been previously unlocked.
  // See Global Unlock Sample for sample code.

  const sb = new StringBuilder();

  for (let i = 1; i <= 20; i++) {
    sb.append('This is the original uncompressed string.\r\n');
  }

  const compress = new Compression();
  compress.algorithm = 'deflate';
  // Indicate that the utf-8 byte representation of the string should be compressed.
  compress.charset = 'utf-8';

  const compressedBytes = await compress.compressStringAsync(sb.getAsString());

  // If the compressed data is desired in string format, then get the base64 representation of the bytes.
  compress.encodingMode = 'base64';
  const compressedBase64 = await compress.compressStringENCAsync(sb.getAsString());
  console.log(`Compressed Bytes as Base64: ${compressedBase64}`);

  // Now decompress...
  let decompressedString = compress.decompressString(compressedBytes);
  console.log('The original string after decompressing from binary compressed data:');
  console.log(decompressedString);

  // To decompress from Base64...
  compress.encodingMode = 'base64';
  decompressedString = await compress.decompressStringENCAsync(compressedBase64);
  console.log('The original string after decompressing from Base64:');
  console.log(decompressedString);
}