Skip to content

Instantly share code, notes, and snippets.

@spemer
Last active April 3, 2020 16:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save spemer/77e60f0847058e26048027e3f24f2e4b to your computer and use it in GitHub Desktop.
Save spemer/77e60f0847058e26048027e3f24f2e4b to your computer and use it in GitHub Desktop.
sitemap-posts.js
const fs = require("fs");
const fetch = require("node-fetch");
const prettier = require("prettier");
const getDate = new Date().toISOString();
const fetchUrl = "https://jsonplaceholder.typicode.com/posts";
const YOUR_AWESOME_DOMAIN = "https://website.com";
const formatted = sitemap => prettier.format(sitemap, { parser: "html" });
(async () => {
const fetchPosts = await fetch(fetchUrl)
.then(res => res.json())
.catch(err => console.log(err));
const postList = [];
fetchPosts.forEach(post => postList.push(post.id));
const postListSitemap = `
${postList
.map(id => {
return `
<url>
<loc>${`${YOUR_AWESOME_DOMAIN}/post/${id}`}</loc>
<lastmod>${getDate}</lastmod>
</url>`;
})
.join("")}
`;
const generatedSitemap = `
<?xml version="1.0" encoding="UTF-8"?>
<urlset
xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd"
>
${postListSitemap}
</urlset>
`;
const formattedSitemap = [formatted(generatedSitemap)];
fs.writeFileSync("../public/sitemap-posts.xml", formattedSitemap, "utf8");
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment