返回

使用 NodeJs 生成 Sitemap XML 文件

日志

const fs = require('fs');
const path = require('path');
const moment = require('moment');

// 获取当前时间
const currentDate = moment().format('YYYY-MM-DD');

// 网站的基本 URL
const baseUrl = 'https://www.example.com';

// 要生成的 Sitemap URL 的集合
const sitemapUrls = [];

// 循环生成博客文章的 Sitemap URL
const blogPosts = [
  {
    title: '文章标题 1',
    slug: 'article-slug-1',
    date: '2023-01-01'
  },
  {
    title: '文章标题 2',
    slug: 'article-slug-2',
    date: '2023-01-02'
  },
  // ...更多博客文章
];

blogPosts.forEach((post) => {
  sitemapUrls.push({
    loc: `${baseUrl}/blog/${post.slug}`,
    lastmod: post.date
  });
});

// 循环生成其他页面的 Sitemap URL
const otherPages = [
  {
    loc: `${baseUrl}/about`,
    lastmod: '2023-01-03'
  },
  {
    loc: `${baseUrl}/contact`,
    lastmod: '2023-01-04'
  },
  // ...更多页面
];

otherPages.forEach((page) => {
  sitemapUrls.push(page);
});

// 生成 Sitemap XML
const xml = `<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
  ${sitemapUrls.map((url) => {
    return `
      <url>
        <loc>${url.loc}</loc>
        <lastmod>${url.lastmod}</lastmod>
      </url>
    `;
  }).join('')}
</urlset>`;

// 保存 Sitemap XML 文件
fs.writeFileSync(path.join(__dirname, 'sitemap.xml'), xml);

console.log('Sitemap XML 已生成。');

这个脚本将生成符合百度、Bing 和 Google 要求的 Sitemap XML 文件,其中包含博客文章和网站其他页面的 URL。