Sample code for 30+ languages & platforms
React Native

Compressing and Decompressing Files Using Streaming (CompressFile / DecompressFile)

See more Compression Examples

This example demonstrates how to compress a file to a binary format and then restore it using the Chilkat.Compression class. The CompressFile method reads the source file, compresses it using the specified algorithm, and writes the result to a destination file. The DecompressFile method performs the reverse operation, restoring the original file from the compressed data.

Both operations are performed internally in streaming mode, allowing files of any size to be processed efficiently without loading the entire file into memory. The example also includes a simple verification step by comparing file sizes to confirm that the decompressed output matches the original input.

Chilkat React Native Downloads

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

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

  const compress = new Compression();

  // Use the zlib algorithm (recommended for general use)
  compress.algorithm = 'zlib';

  // ------------------------------------------------------------------
  // Compress a file
  // ------------------------------------------------------------------

  const inputFile = 'c:/temp/example.txt';
  const compressedFile = 'c:/temp/example.txt.zlib';

  try {
    await compress.compressFileAsync(inputFile, compressedFile);
  } catch {
    console.log('Compression failed:');
    console.log(compress.lastErrorText);
    return;
  }

  console.log('File compressed successfully:');
  console.log(`  Input:      ${inputFile}`);
  console.log(`  Compressed: ${compressedFile}`);

  // ------------------------------------------------------------------
  // Decompress the file back to its original form
  // ------------------------------------------------------------------

  const decompressedFile = 'c:/temp/example_restored.txt';

  try {
    await compress.decompressFileAsync(compressedFile, decompressedFile);
  } catch {
    console.log('Decompression failed:');
    console.log(compress.lastErrorText);
    return;
  }

  console.log('File decompressed successfully:');
  console.log(`  Output: ${decompressedFile}`);

  // ------------------------------------------------------------------
  // Optional: Verify file sizes (basic sanity check)
  // ------------------------------------------------------------------

  const fac = new FileAccess();

  const originalSize = fac.fileSize(inputFile);
  const restoredSize = fac.fileSize(decompressedFile);

  console.log(`Original file size:   ${originalSize}`);
  console.log(`Restored file size:   ${restoredSize}`);

  if (originalSize === restoredSize) {
    console.log('Sizes match (basic verification successful).');
  } else {
    console.log('Warning: File sizes differ.');
  }
}