使用 Node.JS 和 Javascript 自动生成站点地图sitemap

站点地图是 SEO 优化的一个非常重要的方面。谷歌和其他搜索引擎可以使用站点地图来确定您所有页面的位置以及它们如何链接在一起。在本教程中,我们将使用 Node.JS 和 Express 创建一个自动站点地图。

我将使用 MongoDB 作为数据库工具,但如果您使用 MySQL 或其他工具,您可以轻松地将这些组件换掉。

概念#

大多数网站分为两个模糊的类别:

  • 已创建 URL 的页面(即文章、博客文章等)。
  • 具有很少更改的 URL 的页面(即主页等)。

为了自动化站点地图,我们可以列出我们知道不太可能更改的 URL,然后使用 Javascript 获取新页面的数据库条目并将它们添加到我们的站点地图中。谷歌和其他人会经常抓取这个站点地图,这意味着新的 URL 会自动添加到谷歌。

1. 安装组件#

首先,我们必须安装完成此任务所需的所有组件。下面是我们的 index.js 文件的框架:

    
import express from 'express'
import { SitemapStream, streamToPromise } from 'sitemap'
import mongoose from 'mongoose'

const port = 3000
const app = express()

let sitemap;
app.get('/sitemap.xml', async function(req, res) {
    try {
        // Code to try
    } catch (e) {
        // Catch errors
        console.log(e);
    }
});

app.listen(port, function() {
    console.log(`Listening on port ${port}`)
});

本演示需要的两个主要组件是 express、mongoose 和站点地图。如前所述,我使用的是 MongoDB,所以这里 mongoose 是相关的。对于其他人,您可能必须使用不同的包。所有这些都可以使用以下命令安装:

npm i express
npm i sitemap
npm i mongoose

2. 获取您的数据库内容#

在我们开始之前,让我们获取我们的数据库内容。使用 MongoDB 和 mongoose,我可以执行以下操作来获取我的数据库内容:

const allArticles = await Article.Article.find({ published: true }).select('name')
const allCategories = await Category.Category.find().select('name')

现在我们有一个包含所有数据的数组,这些数据引用了不同的文章和类别,所有这些都有一个 URL。接下来,让我们将所有数据映射到一个简单的 URL 数组:

const articles = queryArticles.map( ({ name }) => `/article/${name}`)
const categories = queryCategories.map( ({ name }) => `/category/${name}`)

3. 与站点地图结合现在让我们将所有这些 URL 写入我们的站点地图。我们将每篇文章和类别 URL 写入一个流,然后将其发布给查看站点地图的任何人。我们的 sitemap.xml 路由的最终代码如下所示:

app.get('/sitemap.xml', async function(req, res) 
{ 
res.header('Content-Type', 'application/xml'); 
res.header('Content-Encoding', 'gzip'); 
if (sitemap) { 
res.send(sitemap) return } 
try { 
const allArticles = await Article.Article.find({ published: true }).select('name')
 const allCategories = await Category.Category.find().select('name')
 const articles = queryArticles.map( ({ name }) => `/article/${name}`)
 const categories = queryCategories.map( ({ name }) => `/category/${name}`) // Change yourWebsite.com to your website's URL
 const smStream = new SitemapStream({ hostname: 'https://yourWebsite.com/' })
 const pipeline = smStream.pipe(createGzip()) // Add each article URL to the stream
 articles.forEach(function(item) { // Update as required
 smStream.write({ url: item, changefreq: 'weekly', priority: 0.8}) }); // Add each category URL to the stream
 categories.forEach(function(item) { // Update as required
 smStream.write({ url: item, changefreq: 'monthly', priority: 0.6}) }); // cache the response
 streamToPromise(pipeline).then(sm => sitemap = sm) smStream.end() // Show errors and response
 pipeline.pipe(res).on('error', (e) => {throw e}) } catch (e) { console.error(e) res.status(500).end() } }); 

请注意,在我们的 forEach 循环中,我们提到了更改频率和优先级:更高的优先级意味着这些页面与您的站点更相关。您应该给最重要的页面更高的优先级。更改频率并不一定意味着搜索引擎只会以该频率抓取页面,但它是一个指示。#

4.添加任何其他页面#

如果要添加数据库中未找到的其他页面,只需添加另一smStream.write行。例如:

    smStream.write({ url: '/about', changefreq: 'monthly', priority: 0.4})

5. 在谷歌上索引它#

伟大的!现在你有一个站点地图,它是实时的。我建议您使用 Google 的Search Console来确保在“站点地图”部分下为您的域注册站点地图。

不要忘记更新您的 robots.txt 文件,其中包含指向您的站点地图的链接!

User-agent: *
Allow: /

Sitemap: https://www.code8cn.com/sitemap.xml

通过这些简单的步骤,您已经稍微改进了您的 SEO 游戏。