SnappyJS

0.7.0 · active · verified Tue Apr 21

SnappyJS is a pure JavaScript implementation of Google's Snappy compression algorithm, designed for both Node.js and browser environments. The current stable version is 0.7.0. While there isn't an explicit, regular release cadence, updates appear to be driven by feature additions and maintenance, as indicated by the recent minor version bumps (e.g., 0.7.0, 0.6.1, 0.5.0). Its primary differentiator is being entirely written in JavaScript, leveraging `ArrayBuffer` for efficient handling of binary data. This allows it to run without native dependencies, making it highly suitable for web applications and environments where native modules might be problematic or undesirable. Benchmarks suggest that it achieves approximately 35%-45% of the performance of native Snappy implementations for larger inputs in Node.js, though it can occasionally outperform native solutions for very small input sizes due to lower FFI (Foreign Function Interface) overhead. It's a reliable choice for client-side compression needs or Node.js projects prioritizing pure JS solutions.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to import SnappyJS, convert a string to an `ArrayBuffer`, then compress and uncompress the data, including verification and using the `maxLength` security feature.

import * as SnappyJS from 'snappyjs';

// Example data: a simple text string converted to a Uint8Array
const text = "Hello, SnappyJS! This is a test string to demonstrate compression and decompression.";
const encoder = new TextEncoder();
const originalData = encoder.encode(text);

// SnappyJS expects ArrayBuffer, Buffer, or Uint8Array. 
// Uint8Array's .buffer property provides the underlying ArrayBuffer.
const inputBuffer = originalData.buffer;

console.log(`Original text: "${text}"`);
console.log('Original size:', inputBuffer.byteLength, 'bytes');

try {
  // Compress the data
  const compressed = SnappyJS.compress(inputBuffer);
  console.log('Compressed size:', compressed.byteLength, 'bytes');

  // Uncompress the data
  // Using maxLength as a security measure, estimating twice the original size as a safe upper bound.
  const estimatedMaxLength = inputBuffer.byteLength * 2;
  const uncompressed = SnappyJS.uncompress(compressed, estimatedMaxLength);
  console.log('Uncompressed size:', uncompressed.byteLength, 'bytes');

  // Convert back to string to verify
  const decoder = new TextDecoder();
  const decompressedText = decoder.decode(uncompressed);
  console.log('Decompressed text:', decompressedText);

  if (text === decompressedText) {
    console.log("Compression and decompression successful and data integrity maintained!");
  } else {
    console.error("Error: Data mismatch after compression/decompression!");
  }
} catch (error) {
  console.error("An error occurred during SnappyJS operation:", error.message);
}

view raw JSON →