Sample code for 30+ languages & platforms
React Native

Compress Text from StringBuilder to Gzip (BinData Output)

See more Gzip Examples

This example demonstrates how to use the CompressSb method to compress text stored in a StringBuilder into Gzip format.

The text is first converted to its byte representation using the specified character set (in this case, UTF-8). These bytes are then compressed, and the resulting Gzip data is written to a BinData object in memory.

This approach is useful when working with dynamically generated text that you want to compress without first writing it to a file. The example also shows how the compressed data can optionally be saved to a .gz file.

Chilkat React Native Downloads

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

async function chilkatExample() {
  // This example demonstrates how to compress text contained in a StringBuilder
  // into Gzip format, storing the compressed result in a BinData object.

  const gzip = new Gzip();
  const sb = new StringBuilder();
  const bd = new BinData();

  // Add some text to the StringBuilder:
  sb.append('The quick brown fox jumps over the lazy dog.');

  // Compress the text using UTF-8 encoding:
  try {
    await gzip.compressSbAsync(sb, 'utf-8', bd);
  } catch {
    console.log(gzip.lastErrorText);
    return;
  }

  // The BinData now contains the Gzip-compressed bytes.
  console.log('Compression successful.');
  console.log(`Compressed size (bytes): ${bd.numBytes}`);

  // (Optional) Save to a .gz file:
  try {
    bd.writeFile('text.gz');
  } catch {
    console.log(bd.lastErrorText);
    return;
  }

  console.log('Gzip file written to text.gz');
}