-
Notifications
You must be signed in to change notification settings - Fork 2
/
server.js
64 lines (48 loc) · 1.66 KB
/
server.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
52
53
54
55
56
57
58
59
60
61
62
63
64
const express = require('express');
const fs = require('fs');
const cron = require('node-cron');
const generateSitemap = require('./generate-sitemap');
const app = express();
app.get('/sitemap.xml', (req, res) => {
const maxAge = 3600; // 1 hour
fs.readFile('static/sitemap.xml', (err, data) => {
if (err) {
console.error(err);
res.status(500).send('Error reading sitemap.xml file');
return;
}
res.set({
'Cache-Control': 'public, max-age=' + maxAge,
'Content-Type': 'text/xml'
});
res.send(data);
});
});
const sleep = (seconds) => new Promise((resolve) => setTimeout(resolve, seconds * 1000));
const generateSitemapAndLog = async () => {
const time = new Date().toISOString();
let retryCount = 0;
let sleepSeconds = 10;
let retryLimit = 15;
while (retryCount < retryLimit) {
try {
await generateSitemap();
console.log(`[${time}] sitemap generated successfully.`);
break;
} catch (error) {
console.error(`[[${time}] Error generating sitemap (attempt ${retryCount + 1}/${retryLimit}): `, error);
retryCount++;
if (retryCount < retryLimit) {
await sleep(sleepSeconds);
// if not successful after 15 tries, it will not run again until the next cron schedule
}
}
}
};
// generate sitemap every 24 hours
cron.schedule('0 0 * * *', generateSitemapAndLog);
let port = process.env.PORT || 3012;
app.listen(port, async () => {
console.log(`Server listening on port ${port}`);
await generateSitemapAndLog();
});