precompress

tcmts.cli.web.precompress · #q2ih6tdy · term · runs on the server

uses node:path

Compressed copies beside a file worth compressing (.br, .gz), made once, where they're smaller: what's served to browsers that accept them.

import { COMPRESSIBLE, writeWhole } from "#codebase/tcmts/cli/web";
import fs from "node:fs";
import path from "node:path";
import zlib from "node:zlib";

export function precompress(file: string) {
  if (!COMPRESSIBLE.has(path.extname(file))) return;
  const data = fs.readFileSync(file);
  if (data.length < 128) return;
  const write = (to: string, make: () => Buffer) => {
    if (fs.existsSync(to)) return;
    const packed = make();
    // (whole: another build may be compressing it too, and a server serving it)
    if (packed.length < data.length) writeWhole(to, packed);
  };
  write(`${file}.br`, () =>
    zlib.brotliCompressSync(data, {
      params: {
        [zlib.constants.BROTLI_PARAM_QUALITY]: 11,
        [zlib.constants.BROTLI_PARAM_SIZE_HINT]: data.length,
      },
    }),
  );
  write(`${file}.gz`, () => zlib.gzipSync(data, { level: 9 }));
}

uses

used by