SoFunction
Updated on 2025-03-03

Example of method for NodeJs to generate sitemap sitemap

If the blog is managed using Hexo, sitemap can be generated using plugins. But for a content management website, the backend may be frameworks such as express and koa. At this time, the sitemap needs to be generated by itself.

What is sitemap

Sitemap is a convenient way for website administrators to notify search engines of what pages are available for crawling on their website. The simplest form of Sitemap is an XML file that lists the URLs in the website and other metadata about each URL (when it was last updated, how often it changed, and how important it is relative to other URLs on the website, etc.) so that search engines can crawl the website more intelligently.

sitemap structure

<url>
 <loc>/</loc>
 <lastmod>2019-05-01</lastmod>
 <changefreq>daily</changefreq>
 <priority>0.5</priority>
</url>
  • loc: Article link address
  • lastmod: Last updated time
  • changefreq: update frequency, daily/monthly
  • priority: weight

Generate sitemap, based on express project

Open source package: sitemap, address:/ekalinin/

> npm install --save sitemap

Used in the code

const express = require('express')
const sm = require('sitemap');

('/', function (req, res) {
 let pageRequest = ({});
  = -1;
  = 1;
 ('/article/list', pageRequest, function (result) {
  let urls = [];
  for (let article in result) {
   ({
    url: ,
    changefreq: 'daily',
    lastmodrealtime: true,
    priority: 1,
    lastmod: 
   });
  }

  let sitemap = ({
   hostname: '',
   cacheTime: 600000, // 600sec, cache purge period
   urls: urls
  });

  (function (err, xml) {
   if (err) {
    (err);
    return (500).end();
   }
   ('Content-Type', 'application/xml');
   (xml);
  });
 });
});

sitemap optimization

The above method can still be used when there are fewer articles. If there are thousands or even tens of thousands of articles, the method of pulling it in one go is not suitable. You need to write the return result into the file and update it once a day. Just need to just put

()

Change to

("app/assets/", ());Just do it. Read the file every time you request sitemap

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.