forked from ai/easings.net
-
Notifications
You must be signed in to change notification settings - Fork 0
/
start.js
79 lines (68 loc) · 1.84 KB
/
start.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
const fs = require("fs");
const path = require("path");
const yamlParse = require("js-yaml");
const Parcel = require("parcel-bundler");
const app = require("express")();
const Mustache = require("mustache");
const format = require("./helpers/format");
const i18nDir = path.join(__dirname, "i18n");
const langList = fs
.readdirSync(i18nDir)
.filter(filename => !/^_/.test(filename))
.filter(filename => /\.ya?ml$/i.test(filename))
.map(filename => fs.readFileSync(path.join(i18nDir, filename)))
.map(file => yamlParse.load(file))
.filter(dic => dic.version && dic.version > 1 && dic.lang_name)
.map(dic => ({
code: dic.lang_code,
name: dic.lang_name
}));
const bundler = new Parcel("./src/*.pug", {
watch: true,
hmr: true
});
app.use("/", renderIndexPage);
app.use("/:lang", renderIndexPage);
app.use(bundler.middleware());
app.listen(1234);
function renderIndexPage(req, res, next) {
if (
req.originalUrl === "/" ||
(req.params.lang && req.params.lang.match(/^[a-zA-Z]{2}$/))
) {
const lang = req.params.lang;
bundler.bundle().then(data => {
let indexHtml = "";
if (data.type === "html") {
indexHtml = data.entryAsset.generated.html;
} else {
data.childBundles.forEach(item => {
if (item.entryAsset.id === "index.pug") {
indexHtml = item.entryAsset.generated.html;
}
});
}
try {
const langFile = fs.readFileSync(
`./i18n/${lang ? lang : "en"}.yml`,
"utf8"
);
const viewData = yamlParse.load(langFile);
if (viewData.version >= 2) {
res.send(
Mustache.render(indexHtml, format(viewData, lang, langList))
);
} else {
res.writeHead(406);
res.end("The translation must be at least the 2nd version!");
}
} catch (e) {
console.log(e);
res.writeHead(404);
res.end("The translation does not exist!");
}
});
} else {
next();
}
}