WishMeLz

生活其实很有趣

nodejs 生成网站sitemap.xml

const mysql = require('mysql2')
const fs = require('fs')
const xml2js = require('xml2js')
const path = require('path') // 引入 path 模块以处理路径

// 配置数据库连接
const dbConfig = {
    host: 'localhost',
    port: '3306',
    user: '',
    password: '',
    database: '',
}

// 创建数据库连接
const pool = mysql.createPool(dbConfig)

// 查询数据库获取数据
function fetchDataFromDB() {
    return new Promise((resolve, reject) => {
        pool.query(
            'SELECT id, created_at, updated_at, title FROM simple_topic ORDER BY id DESC',
            (err, results) => {
                if (err) {
                    return reject(err)
                }
                resolve(results)
            },
        )
    })
}

// 生成sitemap.xml文件
async function generateSitemap(data) {
    const urlset = {
        urlset: {
            $: { xmlns: 'http://www.sitemaps.org/schemas/sitemap/0.9' },
            url: data.map((row) => ({
                loc: [`https://xxxx.com/t/${row.id}.html`],
                lastmod: [
                    new Date(row.updated_at * 1000).toLocaleDateString('en-CA'),
                ], 
                changefreq: ['monthly'],
                priority: ['0.5'],
            })),
        },
    }

    const builder = new xml2js.Builder()
    const xml = builder.buildObject(urlset)

    // 获取脚本文件所在目录的上一级目录
    const outputDir = path.join(__dirname, '..', 'sitemap.xml')

    // 将 XML 写入上一级目录
    fs.writeFileSync(outputDir, xml, 'utf-8')
    console.log('Sitemap generated successfully at:', outputDir)
}

async function start() {
    try {
        const data = await fetchDataFromDB()
        if (data.length) {
            await generateSitemap(data)
        } else {
            console.log('No data found to generate sitemap.')
        }
    } catch (error) {
        console.error('Error fetching data or generating sitemap:', error)
    }
}

start()

console.log(new Date().toLocaleDateString('en-CA'))

console.log('Sitemap generator running...')