Skip to content

Instantly share code, notes, and snippets.

@isurfer21
Last active March 6, 2024 06:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save isurfer21/55fbf96e005f8b1357d06686f50e6dc4 to your computer and use it in GitHub Desktop.
Save isurfer21/55fbf96e005f8b1357d06686f50e6dc4 to your computer and use it in GitHub Desktop.
The md2htm is a CLI utility that converts markdown to HTML using bun & pandoc
#!/usr/bin/env bun
import { parseArgs } from "node:util";
const VERSION = '1.0.0';
const { values, positionals } = parseArgs({
args: Bun.argv,
options: {
file: {
type: "string",
short: "f",
},
mold: {
type: "string",
short: "m",
},
title: {
type: "string",
short: "t",
},
brief: {
type: "string",
short: "b",
},
help: {
type: "boolean",
short: "h",
},
version: {
type: "boolean",
short: "v",
},
},
strict: true,
allowPositionals: true,
});
// console.log(values, positionals);
if (values.help) {
console.log(`Usage:
md2htm <file> [options]
i.e.,
bun run md2htm.js <file> [options]
where,
<file> Provide the filename
Options:
-m --mold Provide the webpage template filepath
-t --title Provide the webpage title
-b --brief Provide the webpage description
-h --help Display the help menu
-v --version Display the version of app
Examples:
md2htm -h
md2htm help.md -t Help -b "Help manual for web, app & API" -m template.htm
md2htm help.htm -t Help -b "Help manual for web, app & API" -m template.htm
`);
} else if (values.version) {
console.log(`md2htm - markdown to html
Converts markdown to html using bun & pandoc
Version ${VERSION}`);
} else {
const filePath = positionals[2];
const fileExt = filePath.substring(filePath.lastIndexOf("."));
let fileContent;
if (fileExt == ".md") {
const proc = Bun.spawn(["pandoc", "-f", "markdown", filePath]);
fileContent = await new Response(proc.stdout).text();
} else {
const fileRef = Bun.file(filePath);
fileContent = await fileRef.text();
}
if (!!values.mold) {
const templateRef = Bun.file(values.mold);
let targetContent = await templateRef.text();
targetContent = targetContent
.replace("{{content}}", fileContent)
.replace("{{title}}", values.title || "")
.replace("{{brief}}", values.brief || "");
await Bun.write(`${filePath}.html`, targetContent);
console.log("Success!");
} else {
console.log("Failed! Template file is missing.");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment