Compression Streams API를 이용한 텍스트 데이터에 대한 압축 및 해제

Compression Streams API는 웹 표준 API로 데이터에 대한 압축 및 해제를 위한 API이다. 파일 단위가 아닌 데이터에 대한 압축으로 그 목적이 zip과는 다르지만 데이터 압축에 대한 알고리즘은 유사하다. 즉, zip은 여러개의 파일을 압축하면서 압축 해제시에는 파일 명과 디렉토리 구조까지 복원해주지만 Compression Sterams API는 데이터에 대한 압축으로 압축을 해제하면 해제된 데이터가 나오며 그 데이터를 하나의 파일로 저장한다.

Compression Streams API로 압축할 수 있는 데이터는 텍스트 든 바이너리든 모두 가능한데, 아래의 코드는 텍스트에 대한 압축과 압축된 데이터를 다시 원래의 텍스트 데이터로 복원(압축 해제)하는 코드이다.

async function compressAndDecompressString(text) {
  // 1. 텍스트를 Uint8Array로 변환
  const textEncoder = new TextEncoder();
  const encodedData = textEncoder.encode(text);

  console.log("원본 데이터:", text);
  console.log("원본 데이터 크기 (바이트):", encodedData.byteLength);

  // 2. 데이터를 압축 (gzip 형식)
  // ReadableStream.from()은 Node.js에서 사용 가능하며, 
  // 브라우저에서는 ArrayBuffer를 직접 ReadableStream으로 변환해야 함.
  // 여기서는 편의를 위해 Blob을 사용하여 ReadableStream을 생성합니다.
  const originalStream = new Blob([encodedData]).stream();
  const compressedStream = originalStream.pipeThrough(new CompressionStream("gzip"));

  // 3. 압축된 데이터를 ArrayBuffer로 읽기
  const compressedResponse = new Response(compressedStream);
  const compressedBuffer = await compressedResponse.arrayBuffer();

  console.log("압축된 데이터 크기 (바이트):", compressedBuffer.byteLength);
  console.log("압축률:", 
    ((1 - compressedBuffer.byteLength / encodedData.byteLength) * 100).toFixed(2) + "%");

  // 4. 압축된 데이터를 압축 해제
  const decompressedStream = new Blob([compressedBuffer]).stream()
    .pipeThrough(new DecompressionStream("gzip"));

  // 5. 압축 해제된 데이터를 ArrayBuffer로 읽기
  const decompressedResponse = new Response(decompressedStream);
  const decompressedBuffer = await decompressedResponse.arrayBuffer();

  // 6. 압축 해제된 Uint8Array를 다시 텍스트로 변환
  const textDecoder = new TextDecoder();
  const decompressedText = textDecoder.decode(decompressedBuffer);

  console.log("압축 해제된 데이터:", decompressedText);
  console.log("압축 해제된 데이터 크기 (바이트):", decompressedBuffer.byteLength);

  // 원본 데이터와 압축 해제된 데이터가 동일한지 확인
  console.log("원본과 압축 해제된 데이터 일치 여부:", text === decompressedText);
}

// 예제 실행
const longText = `The quick brown fox jumps over the lazy dog.`;

compressAndDecompressString(longText);

SharedArrayBuffer

SharedArrayBuffer는 웹에서 스레드 간의 공유 메모리로 사용된다. 메인 스레드에서 4바이트 크기의 메모리 만들고 이를 공유해 웹워커에서 이 4바이트의 데이터를 정수값으로 해석해 값을 1 증가시키는 예제다. 먼저 vite로 프로젝트를 구성했으며 main.js의 코드는 다음과 같다.

if (!crossOriginIsolated) {
  throw new Error('SharedArrayBuffer를 사용하려면 crossOriginIsolated 환경이어야 합니다.');
}

const worker = new Worker('./worker.js');
const buffer = new SharedArrayBuffer(4);
const view = new Int32Array(buffer);

view[0] = 42;

worker.postMessage({ buffer });

setTimeout(() => {
  console.log('메인에서 읽기:', view[0]);
}, 500);

이 시점에서는 2가지 문제가 발생해야 한다. 첫번째는 조건문 if에 대한 crossOriginIsolated를 통과하지 못한다. 이는 SharedArrayBuffer를 이용하기 위해서는 crossOriginIsolated가 설정되어야 한다. 두번째는 worker.js 파일이 존재하지 않는다. 첫번째 문제를 해결하기 위해서 먼저 다음과 같은 개발환경을 위한 패키지를 설치해야 한다.

npm install -D vite-plugin-cross-origin-isolation

그리고 vite.config.js 파일을 열어, 없다면 생성해서 다음처럼 플러그인을 추가한다.

import { defineConfig } from 'vite'
import crossOriginIsolation from "vite-plugin-cross-origin-isolation";

export default defineConfig({
  plugins: [
    crossOriginIsolation(),
  ],
})

두번째 문제인 worker.js 파일을 public 폴더에 생성하고 다음처럼 작성한다.

self.onmessage = (event) => {
  const buffer = event.data.buffer;
  const view = new Int32Array(buffer);

  console.log('워커에서 읽기:', view[0]);

  // view[0] += 1;
  Atomics.add(view, 0, 1);

  console.log('워커에서 변경:', view[0]);
}

값을 1 더하는 코드는 Atomics API를 이용해 데이터 경쟁이 발생하지 않도록 하는 것이 바람직하다.