-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
81 lines (65 loc) · 2.22 KB
/
app.js
File metadata and controls
81 lines (65 loc) · 2.22 KB
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
'use strict';
const fs = require('fs');
const path = require('path');
// const os = require('os');
const express = require('express');
const app = express(); // express instance
// static assets
app.use('/assets', express.static(path.join(__dirname, 'assets')));
const list = require('./pgn.json').list;
const pgn = {};
list.forEach(item => {
pgn[item.date] = item;
});
const chessTemplate = fs.readFileSync(path.join(__dirname, 'template', 'chess.html'), 'utf-8');
const indexTemplate = fs.readFileSync(path.join(__dirname, 'template', 'index.html'), 'utf-8');
const genIndexHTML = require('./util/genIndexHTML');
const parsePGN = require('./util/parsePGN');
const eco = require('./eco.json');
const strIndexHTML = genIndexHTML(list);
app.get('/:date', (req, res) => {
const date = req.params.date;
if (pgn[date]) {
const item = pgn[date];
const pgnPath = path.join(__dirname, 'pgn', `${item.date}-${item.id}.pgn`);
if (fs.existsSync(pgnPath)) {
const pgnContent = fs.readFileSync(pgnPath);
const pgnObj = parsePGN(pgnContent.toString());
const players = item.players.split(' vs ');
const data = {
title: `${item.players} (${item.year}) ${item.note}`,
player1: players[0],
player2: players[1],
note: item.note,
date: item.date,
pgn: pgnObj.pgnText,
notes: pgnObj.notes,
opening: pgnObj.ECO,
result: pgnObj.Result,
info: `${pgnObj.Event} (${pgnObj.Date}), ${pgnObj.Site}`
};
if (eco[pgnObj.ECO]) {
data.opening = `${eco[pgnObj.ECO].name}(${pgnObj.ECO})`;
}
const ret = chessTemplate.replace(/\${([^}]*)}/g, (content, name) => {
// replace sigle quote to avoid parse error
if (name === 'pgn') return data.pgn.replace(/'/g, '’');
return data[name] || '';
});
res.send(ret)
} else {
res.send('PGN file not found.');
}
} else {
res.send('404');
}
});
app.get('/', (req, res) => {
let ret = indexTemplate.replace('${content}', strIndexHTML);
res.send(ret);
});
// listen local port 2000
const server = app.listen(2000, function () {
const port = server.address().port;
console.log('Project listening at http://localhost:%s', port);
});