Created
October 30, 2022 20:48
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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