the home site for me: also iteration 3 or 4 of my site
1import puppeteer from "puppeteer";
2import { readdir } from "node:fs/promises";
3
4const template = await Bun.file("tools/og.html").text();
5
6const browser = await puppeteer.launch();
7
8async function og(
9 postname: string,
10 outputPath: string,
11 width = 1200,
12 height = 630
13) {
14 const page = await browser.newPage();
15
16 await page.setViewport({ width, height });
17
18 await page.setContent(template.toString().replace("{{postname}}", postname));
19
20 await page.screenshot({ path: outputPath });
21}
22
23async function fileExists(path: string): Promise<boolean> {
24 try {
25 await Bun.file(path);
26 return true;
27 } catch (e) {
28 return false;
29 }
30}
31
32try {
33 // check if the public/blog folder exists
34 // if not exit
35 // if it does, get all the folders and then get the title tag from the index.html
36
37 if (!(await fileExists("public/"))) {
38 console.error("public/ does not exist");
39 process.exit(1);
40 }
41
42 // read all the files in the current directory filtering for index.htmls
43 const files = (await readdir("public/", { recursive: true })).filter((file) =>
44 file.endsWith("index.html")
45 );
46
47 console.log("Generating OG images for", files.length, "files");
48
49 // for each file, get the title tag from the index.html
50 for (const file of files) {
51 const index = await Bun.file(`public/${file}`).text();
52 const title = index.match(/<title>(.*?)<\/title>/)![1];
53 if (!title) {
54 console.error(`No title found for ${file}`);
55 continue;
56 }
57 console.log("Generating OG for", title);
58 await og(title, `public/${file.replace("index.html", "og.png")}`);
59 }
60} catch (e) {
61 console.error(e);
62} finally {
63 await browser.close();
64}