Skip to content

Instantly share code, notes, and snippets.

@joranquinten
Created October 30, 2022 20:48
Show Gist options
  • Save joranquinten/76a6727f9108831a06b97e77b18b6dca to your computer and use it in GitHub Desktop.
Save joranquinten/76a6727f9108831a06b97e77b18b6dca to your computer and use it in GitHub Desktop.
Small node script that generates a sitemap xml based in a folder and its subfolders (assuming they each represent an individual page). Works well after rendering an SSR generated website.
const fs = require("fs");
const path = require("path");
const config = require("./package.json"); // Please add a "url" field to the package.json to serve as base domain
const ignoreFolders = ["_nuxt"]; // Modify if you see fit
const readFolder = "./dist"; // The location where static files are generated
const outputFile = "sitemap.xml" // The location to store the sitemap (placed at the root of the readFolder)
function flatten(lists) {
return lists.reduce((a, b) => a.concat(b), []);
}
function getDirectories(srcpath) {
return fs
.readdirSync(srcpath)
.filter((path) => !ignoreFolders.includes(path))
.map((file) => path.join(srcpath, file))
.filter((path) => fs.statSync(path).isDirectory());
}
function getDirectoriesRecursive(srcpath) {
return [
srcpath,
...flatten(getDirectories(srcpath).map(getDirectoriesRecursive)),
];
}
const grabFolders = (readFolder) =>
getDirectoriesRecursive(readFolder).map((f) =>
`${config.url}/`.concat(f.replace("dist/", "")).replace(readFolder, "")
);
const generateSitemap = (readFolder, outputfile) => {
const folders = grabFolders(readFolder);
const today = new Date();
const formattedDate = today.toISOString().split("T")[0];
const formattedFolders = folders
.map(
(f) => `
<url>
<loc>${f}</loc>
<lastmod>${formattedDate}</lastmod>
</url>`
)
.join("");
const xml = `<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
${formattedFolders}
</urlset>`;
fs.writeFile(outputfile, xml, (err) => {
if (err) {
console.error(err);
}
console.log(`XML file generated at ${outputfile}`);
});
};
generateSitemap(readFolder, `${readFolder}/${outputFile}`);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment