Files
blog/build.js
wholteza 24fd81c32c Initial commit
Static site generation from md wip
2023-09-15 22:35:15 +02:00

70 lines
1.7 KiB
JavaScript

import * as fs from "fs";
const paths = {
output: ".dist",
notes: {
root: "notes",
assets: "assets",
note: "note.md",
},
templates: {
root: "templates",
note: "note.html",
index: "index.html",
notFound: "404.html",
},
};
if (fs.readdirSync(".").includes(paths.output)) {
fs.rmSync(paths.output, { recursive: true, force: true });
}
fs.mkdirSync(paths.output);
const directoryNames = fs.readdirSync(paths.notes.root);
const manifest = directoryNames.map((noteDirectory) => ({
directoryName: noteDirectory,
name: noteDirectory,
markdown: fs.readFileSync(
`${paths.notes.root}/${noteDirectory}/${paths.notes.note}`,
{ encoding: "utf-8" }
),
assetDirectoryPath: `${paths.notes.root}/${noteDirectory}/${paths.notes.assets}`,
}));
manifest.forEach((m) => {
const notePath = `${paths.templates.root}/${paths.templates.note}`;
let htmlTemplate = fs.readFileSync(notePath, {
encoding: "utf-8",
});
htmlTemplate = htmlTemplate.replace("{{markdown}}", m.markdown);
fs.writeFileSync(`${paths.output}/${m.directoryName}.html`, htmlTemplate, {
encoding: "utf-8",
flag: "ax",
});
});
[paths.templates.notFound].forEach((filename) => {
fs.copyFileSync(
`${paths.templates.root}/${filename}`,
`${paths.output}/${filename}`
);
});
let htmlTemplate = fs.readFileSync(
`${paths.templates.root}/${paths.templates.index}`,
{
encoding: "utf-8",
}
);
const links = manifest.map(
(m) => `<a href='/${m.directoryName}.html'>${m.name}</a>`
);
htmlTemplate = htmlTemplate.replace("{{content}}", links);
fs.writeFileSync(`${paths.output}/index.html`, htmlTemplate, {
encoding: "utf-8",
flag: "ax",
});
console.log(manifest);