Skip to content

Instantly share code, notes, and snippets.

@nshun
Created October 28, 2018 12:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nshun/cbe561819f26594be9a1a690928fd91c to your computer and use it in GitHub Desktop.
Save nshun/cbe561819f26594be9a1a690928fd91c to your computer and use it in GitHub Desktop.
This is sitemap.xml generator for nextjs. forked from https://gist.github.com/evantahler/ba75e277c756fce337b7370035b298e7 .
#! /usr/bin/env node
// I am ./bin/buildSitemap.js
const path = require('path')
const glob = require('glob')
const fs = require('fs')
const SITE_ROOT = process.env.SITE_ROOT || 'https://nshun.net'
const SOURCE = process.env.SOURCE || path.join(__dirname, '../..', 'docs', '/**/*.html')
const DESTINATION = process.env.DESTINATION || path.join(__dirname, '../..', 'docs/static', 'sitemap.xml')
let diskPages = glob.sync(SOURCE)
let xml = ''
xml += '<?xml version="1.0" encoding="UTF-8"?>'
xml += '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">'
diskPages.forEach((page) => {
page = path.normalize(page)
let stats = fs.statSync(page)
let modDate = new Date(stats.mtime)
let lastMod = `${modDate.getFullYear()}-${('0' + (modDate.getMonth() + 1)).slice(-2)}-${('0' + modDate.getDate()).slice(-2)}`
console.log(path.join(__dirname, '../..', 'docs')+' in '+page)
page = page.replace(path.join(__dirname, '../..', 'docs'), '')
console.log(page)
page = page.replace(/.html$/, '')
page = `${SITE_ROOT}${page}`
if (/.*[\/\\]index$/.test(page)) {
page = page.replace(/(.*)index$/, '$1')
}
page = page.split(path.sep).join('/')
xml += '<url>'
xml += `<loc>${page}</loc>`
xml += `<lastmod>${lastMod}</lastmod>`
xml += `<changefreq>always</changefreq>`
xml += `<priority>0.5</priority>`
xml += '</url>'
})
xml += '</urlset>'
fs.writeFileSync(DESTINATION, xml)
console.log(`Wrote sitemap for ${diskPages.length} pages to ${DESTINATION}`)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment