the home site for me: also iteration 3 or 4 of my site
1import puppeteer from "puppeteer"; 2import { readdir, mkdir } 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 const directories = new Set( 48 files.map((file) => file.replace("index.html", "")) 49 ); 50 51 const existing = (await readdir("static/")).filter((file) => 52 directories.has(file) 53 ); 54 55 // create not existing 56 for (const dir of directories) { 57 if (!existing.includes(dir)) { 58 await mkdir(`static/${dir.split("/").slice(0, -1).join("/")}`, { 59 recursive: true, 60 }); 61 } 62 } 63 64 console.log("Generating OG images for", files.length, "files"); 65 66 // for each file, get the title tag from the index.html 67 for (const file of files) { 68 const index = await Bun.file(`public/${file}`).text(); 69 const title = index.match(/<title>(.*?)<\/title>/)![1]; 70 if (!title) { 71 console.error(`No title found for ${file}`); 72 continue; 73 } 74 75 console.log("Generating OG for", title); 76 await og(title, `static/${file.replace("index.html", "og.png")}`); 77 } 78} catch (e) { 79 console.error(e); 80} finally { 81 await browser.close(); 82}