Skip to content

Commit

Permalink
Add compression logic
Browse files Browse the repository at this point in the history
  • Loading branch information
sondr3 committed Aug 27, 2022
1 parent bfd7439 commit 5b821f3
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 0 deletions.
47 changes: 47 additions & 0 deletions src/compress.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import { globby } from "globby";
import { createReadStream, createWriteStream } from "node:fs";
import { hrtime } from "node:process";
import { promises as stream } from "node:stream";
import { createBrotliCompress, createGzip } from "node:zlib";

import { Logger } from "./logger.js";

const filterFile = (file: string): boolean => {
return [".css", ".js", ".html", ".xml", ".cjs", ".mjs", ".svg", ".txt"].every((ext) =>
file.endsWith(ext),
);
};

export const gzip = async (dir: URL): Promise<void> => {
const start = hrtime.bigint();

const files = (await globby(dir.pathname)).filter(filterFile);
for (const file of files) {
if (filterFile(file)) continue;
const source = createReadStream(file);
const destination = createWriteStream(`${file}.gz`);
const gzip = createGzip({ level: 9 });
await stream.pipeline(source, gzip, destination);
}

const end = hrtime.bigint();

Logger.info(`finished gzip of ${files.length} files in ${(end - start) / 1000000n}m`);
};

export const brotli = async (dir: URL): Promise<void> => {
const start = hrtime.bigint();

const files = (await globby(dir.pathname)).filter(filterFile);
for (const file of files) {
if (filterFile(file)) continue;
const source = createReadStream(file);
const destination = createWriteStream(`${file}.br`);
const brotli = createBrotliCompress();
await stream.pipeline(source, brotli, destination);
}

const end = hrtime.bigint();

Logger.info(`finished brotli of ${files.length} files in ${(end - start) / 1000000n}m`);
};
2 changes: 2 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
import type { AstroIntegration } from "astro";

import { brotli, gzip } from "./compress.js";
import { Logger } from "./logger.js";

export const createCompressionPlugin = (): AstroIntegration => {
return {
name: "astro-compressor",
hooks: {
"astro:build:done": async ({ dir }) => {
await Promise.allSettled([gzip(dir), brotli(dir)]);
Logger.success("Compression finished\n");
},
},
Expand Down

0 comments on commit 5b821f3

Please sign in to comment.