createSiteMap.js 776 字节
Newer Older
D
DCloud_LXH 已提交
1 2 3
const fs = require('fs')
const path = require('path')

D
DCloud_LXH 已提交
4
const domain = 'https://doc.dcloud.net.cn'
D
DCloud_LXH 已提交
5 6 7 8 9 10 11
const xmlBefore = `<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
`
const xmlAfter = `\n</urlset>`

module.exports = (links, callback = () => { }) => {
  const xmlItems = links.map(url => {
D
DCloud_LXH 已提交
12
    if (!url.endsWith('/') && !url.endsWith('html')) url += '.html'
D
DCloud_LXH 已提交
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
    return `  <url>
    <loc>${domain + url}</loc>
  </url>`
  }).join('\n')

  const rootPath = path.resolve(__dirname, '../public')
  const staticExists = fs.existsSync(rootPath)
  if (!staticExists) fs.mkdirSync(rootPath)

  fs.writeFile(
    path.resolve(rootPath, 'sitemap.xml'),
    xmlBefore + xmlItems + xmlAfter,
    { encoding: 'utf-8' },
    callback
  )
}