the home site for me: also iteration 3 or 4 of my site
at v1.0 2.2 kB view raw
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 let title: string; 70 if (file.startsWith("tags/")) { 71 const parts = file.split("/"); 72 title = `Tag: ${parts[1]}`; // take the next directory as the title 73 } else { 74 const match = index.match(/<title>(.*?)<\/title>/); 75 if (match) { 76 title = match[1]; 77 } else { 78 console.error(`No title found for ${file}`); 79 continue; 80 } 81 } 82 83 console.log("Generating OG for", title); 84 await og(title, `static/${file.replace("index.html", "og.png")}`); 85 } 86} catch (e) { 87 console.error(e); 88} finally { 89 await browser.close(); 90}