-
Notifications
You must be signed in to change notification settings - Fork 0
/
sitemap.build.js
51 lines (46 loc) · 1.71 KB
/
sitemap.build.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
const builder = require('xmlbuilder');
const fs = require('fs');
const data = require('./resources/sitemap');
const lastmod = formatDate(new Date());
if(data.entries && data.entries.length) {
generateSitemapIndex();
data.entries.forEach((entry) => {
generateSitemap(`/${entry}`, `sitemap-${entry}.xml`)
});
} else {
generateSitemap('', 'sitemap.xml')
}
function generateSitemapIndex() {
const sitemapIndex = builder.create('sitemapindex')
.att('xmlns', 'http://www.sitemaps.org/schemas/sitemap/0.9');
data.entries.forEach((entry) => {
const sitemap = sitemapIndex.ele('sitemap');
sitemap.ele('loc').txt(`${data.root}/sitemap-${entry}.xml`);
sitemap.ele('lastmod').txt(lastmod);
})
writeXml(`${data.dist}/sitemap.xml`, sitemapIndex);
}
function generateSitemap(entry, filename) {
const sitemap = builder.create('urlset')
.att('xmlns', 'http://www.sitemaps.org/schemas/sitemap/0.9')
.att('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance')
.att('xsi:schemaLocation', 'http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd');
data.routes.forEach((route) => {
const url = sitemap.ele('url');
url.ele('loc').txt(`${data.root}${entry}${route}`);
url.ele('lastmod').txt(lastmod);
});
writeXml(`${data.dist}/${filename}`, sitemap);
}
function writeXml(path, doc) {
fs.writeFile(path, doc.end({pretty: true}).toString(), function (err){
if (err) throw err;
console.log(`file : ${path} has been generated`);
});
}
function formatDate(date) { // 2000-08-03
let formatted = `${date.getFullYear()}-`;
formatted += `0${date.getMonth() + 1}-`.substr(-3);
formatted += `0${date.getDate()}`.substr(-2);
return formatted;
}