Last active
April 3, 2020 16:22
-
-
Save spemer/77e60f0847058e26048027e3f24f2e4b to your computer and use it in GitHub Desktop.
sitemap-posts.js
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 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