Create a sitemap.xml with Node.js and EJS

Create a sitemap.xml with Node.js and EJS

A site map (or sitemap) is a list of pages of a web site allowing users and search engines to find the data faster and more efficiently.

router.get('/sitemap.xml', controller.sitemap)
exports.sitemap = (req, res, next) => {
	//Return an XML content type
  	res.set('Content-Type', 'text/xml')

  	//Get and return data to generate the sitemap
    res.render('html/sitemap', {
        //whatever data you need to show in the sitemap
        article: []
    })
}
<?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">

    <url>
        <loc>https://www.yamicode.com/</loc>
        <lastmod><%=date%></lastmod>
        <changefreq>always</changefreq>
        <priority>1.00</priority>
    </url>
    <% articles.forEach(article=>{ %>
        <url>
            <loc>https://www.yamicode.com/articles/article/<%=article.name%></loc>
            <lastmod><%=article.date.replace(new RegExp('/', 'g'), "-")%></lastmod>
            <changefreq>weekly</changefreq>
            <priority>0.80</priority>
        </url>
    <% }) %>

</urlset>