|
| 1 | +import {readFileSync, writeFileSync} from 'node:fs'; |
| 2 | +import {join} from 'node:path'; |
| 3 | + |
| 4 | +const extractLocalLinks = baseURL => { |
| 5 | + const urls = new Set(); |
| 6 | + const offset = baseURL.length; |
| 7 | + for (const {href} of document.links) { |
| 8 | + if (href.startsWith(baseURL)) { |
| 9 | + const path = href.slice(offset); |
| 10 | + urls.add(path); |
| 11 | + } |
| 12 | + } |
| 13 | + return Array.from(urls); |
| 14 | +}; |
| 15 | + |
| 16 | +const ENTRY_POINT = '/topics'; |
| 17 | +const SITEMAP = join(__dirname, './sitemap.json'); |
| 18 | + |
| 19 | +/** |
| 20 | + * Determines URLs and writes them to disk. |
| 21 | + * |
| 22 | + * @param {string} baseURL - The site's base URL. |
| 23 | + * @param {Object} page - The current page object. |
| 24 | + */ |
| 25 | +const createSiteMap = async (baseURL, page) => { |
| 26 | + await page.goto(baseURL + ENTRY_POINT); |
| 27 | + const urls = await page.evaluate(extractLocalLinks, baseURL); |
| 28 | + const data = JSON.stringify(urls, null, 4); |
| 29 | + writeFileSync(SITEMAP, data, {encoding: 'utf-8'}); |
| 30 | +}; |
| 31 | + |
| 32 | +/** |
| 33 | + * Reads any previously created site map from disk. |
| 34 | + * |
| 35 | + * @return {Object} Sitemap data. |
| 36 | + */ |
| 37 | +const readSiteMap = async () => { |
| 38 | + let data = null; |
| 39 | + try { |
| 40 | + data = readFileSync(SITEMAP, {encoding: 'utf-8'}); |
| 41 | + } catch (err) { |
| 42 | + if (err.code === 'ENOENT') { |
| 43 | + throw new Error('Missing site map'); |
| 44 | + } |
| 45 | + throw err; |
| 46 | + } |
| 47 | + return JSON.parse(data); |
| 48 | +}; |
| 49 | + |
| 50 | +export {createSiteMap, readSiteMap}; |
0 commit comments