Files
Robin Chappatte 45ac405505 initial commit
2024-06-05 17:48:16 +02:00

60 lines
1.8 KiB
TypeScript

import { encodeBase64 } from 'https://deno.land/std@0.224.0/encoding/base64.ts';
import { ensureFile } from 'https://deno.land/std@0.224.0/fs/mod.ts';
/**
* { [path]: base64EncodedContent }
*/
type StaticFilesRecord = Record<string, string>;
/**
* Traverse a directory recursively, adding every base64 encoded file content to the record.
*
* @param staticFileRecord the record in which to add base64 encoded file content
* @param root the path of the root directory for traversal, that should not be included in the record file path
* @param subdir the current subdir to traverse
*/
async function traverse(
staticFileRecord: StaticFilesRecord,
root: string,
subdir: string = '',
) {
for await (const dirEntry of Deno.readDir(`${root}/${subdir}`)) {
const path = `${subdir}/${dirEntry.name}`.slice(1);
console.log(`encoding: ${path}`);
if (dirEntry.isDirectory) {
await traverse(staticFileRecord, root, `${subdir}/${dirEntry.name}`);
} else {
staticFileRecord[path] = encodeBase64(
await Deno.readFile(
`${root}/${subdir}/${dirEntry.name}`,
),
);
}
}
}
/**
* Bundle all files of the given directory into a single json file at the given path.
*
* @param sourceDir path of the directory to bundle
* @param bundleFilePath path of the json file
*/
async function buildFromDir(
sourceDir: string,
bundleFilePath: string,
) {
const staticFiles: StaticFilesRecord = {};
await traverse(staticFiles, sourceDir);
await ensureFile(bundleFilePath);
await Deno.writeTextFile(bundleFilePath, JSON.stringify(staticFiles));
}
if (Deno.args.length !== 2) {
console.error('Incorrect usage: Two parameters expected !');
console.error('<script> view-dist-directory json-bundle-file');
Deno.exit(1);
}
await buildFromDir(Deno.args[0], Deno.args[1]);