76 lines
2.2 KiB
JavaScript
76 lines
2.2 KiB
JavaScript
// scripts/generate-sitemap.js
|
|
const fs = require("fs");
|
|
const path = require("path");
|
|
const { SitemapStream, streamToPromise } = require("sitemap");
|
|
|
|
const hostname = "https://sixty5street.com";
|
|
const addTrailingSlash = true;
|
|
|
|
// Utility to determine if a trailing slash should be added
|
|
const shouldAddSlash = (url) => {
|
|
if (url === "/") return false;
|
|
if (/\.[a-z0-9]{2,6}(\?.*)?$/i.test(url)) return false; // skip files
|
|
return true;
|
|
};
|
|
|
|
// Format URL to ensure proper slashes and handle anchors
|
|
const formatUrl = (url) => {
|
|
// Split path and hash
|
|
let [pathPart, hashPart] = url.split("#");
|
|
|
|
// Remove extra leading slashes and ensure single starting slash
|
|
pathPart = "/" + pathPart.replace(/^\/+/, "");
|
|
|
|
// Add or remove trailing slash for pathPart
|
|
if (addTrailingSlash && shouldAddSlash(pathPart) && !pathPart.endsWith("/")) {
|
|
pathPart += "/";
|
|
}
|
|
if (!addTrailingSlash && pathPart.endsWith("/") && pathPart !== "/") {
|
|
pathPart = pathPart.slice(0, -1);
|
|
}
|
|
|
|
// Recombine with hash if it exists
|
|
return hashPart ? pathPart + "#" + hashPart : pathPart;
|
|
};
|
|
|
|
// List of URLs to include in sitemap
|
|
const sectionLinks = [
|
|
{ url: "/", changefreq: "daily", priority: 1.0 },
|
|
{ url: "/#about", changefreq: "weekly", priority: 0.8 },
|
|
{ url: "/#popular-dishes", changefreq: "monthly", priority: 0.7 },
|
|
{ url: "/#sixty5-street-specials", changefreq: "weekly", priority: 0.8 },
|
|
{ url: "/#menu", changefreq: "weekly", priority: 0.7 },
|
|
];
|
|
|
|
// Format all URLs
|
|
const allLinks = sectionLinks.map((link) => ({
|
|
...link,
|
|
url: formatUrl(link.url),
|
|
}));
|
|
|
|
// Generate sitemap.xml
|
|
async function generateSitemap() {
|
|
try {
|
|
const sitemap = new SitemapStream({ hostname });
|
|
const writeStream = fs.createWriteStream(
|
|
path.resolve(__dirname, "../public/sitemap.xml")
|
|
);
|
|
|
|
sitemap.pipe(writeStream);
|
|
|
|
console.log("📦 Writing URLs to sitemap:");
|
|
allLinks.forEach((link) => {
|
|
console.log(" -", hostname + link.url);
|
|
sitemap.write(link);
|
|
});
|
|
|
|
sitemap.end();
|
|
await streamToPromise(sitemap);
|
|
|
|
console.log("✅ sitemap.xml created successfully!");
|
|
} catch (error) {
|
|
console.error("❌ Error creating sitemap.xml:", error);
|
|
}
|
|
}
|
|
|
|
generateSitemap(); |