forked from nodejs/nodejs.org
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
173 lines (147 loc) · 5.03 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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
'use strict';
// The server where the site is exposed through a static file server
// while developing locally.
const fs = require('fs/promises');
const http = require('http');
const path = require('path');
const chokidar = require('chokidar');
const junk = require('junk');
const st = require('st');
const build = require('./build');
const mount = st({
path: path.join(__dirname, 'build'),
cache: false,
index: 'index.html',
passthrough: true
});
const port = process.env.PORT || 8080;
const selectedLocales = process.env.DEFAULT_LOCALE
? process.env.DEFAULT_LOCALE.toLowerCase().split(',')
: process.env.DEFAULT_LOCALE;
const preserveLocale = process.argv.includes('--preserveLocale');
const serveOnly = process.argv.includes('--serve-only');
// Watches for file changes in the locale, layout and static directories, and
// rebuilds the modified one.
const opts = {
ignoreInitial: true,
usePolling: true
};
const locales = chokidar.watch(path.join(__dirname, 'locale'), opts);
const css = chokidar.watch(path.join(__dirname, 'layouts/css/**/*.scss'), opts);
const layouts = chokidar.watch(path.join(__dirname, 'layouts/**/*.hbs'), opts);
const staticFiles = chokidar.watch(path.join(__dirname, 'static'), opts);
// Gets the locale name by path.
function getLocale(filePath) {
const pre = path.join(__dirname, 'locale');
return filePath.slice(
pre.length + 1,
filePath.indexOf(path.sep, pre.length + 1)
);
}
// This function has two meanings:
// 1. Build for the specific language.
// 2. Choose what languages for the menu.
async function dynamicallyBuildOnLanguages(source, locale) {
let localesData = null;
if (!selectedLocales || selectedLocales.length === 0) {
const localesPath = path.join(__dirname, 'locale');
const locales = await fs.readdir(localesPath);
const filteredLocales = locales.filter((file) => junk.not(file));
localesData = build.generateLocalesData(filteredLocales);
} else {
localesData = build.generateLocalesData(selectedLocales);
}
build.buildLocale(source, locale, { preserveLocale, localesData });
}
build.getSource((err, source) => {
if (err) {
throw err;
}
locales.on('change', async (filePath) => {
const locale = getLocale(filePath);
if (!selectedLocales || selectedLocales.includes(locale)) {
console.log(
`The language ${locale} is changed, '${filePath}' is modified.`
);
await dynamicallyBuildOnLanguages(source, locale);
}
});
locales.on('add', async (filePath) => {
const locale = getLocale(filePath);
if (!selectedLocales || selectedLocales.includes(locale)) {
console.log(`The language ${locale} is changed, '${filePath}' is added.`);
await dynamicallyBuildOnLanguages(source, locale);
locales.add(filePath);
}
});
});
css.on('change', () => build.buildCSS());
css.on('add', (filePath) => {
css.add(filePath);
build.buildCSS();
});
layouts.on('change', () =>
build.fullBuild({ selectedLocales, preserveLocale })
);
layouts.on('add', (filePath) => {
layouts.add(filePath);
build.fullBuild({ selectedLocales, preserveLocale });
});
staticFiles.on('change', build.copyStatic);
staticFiles.on('add', (filePath) => {
staticFiles.add(filePath);
build.copyStatic();
});
const mainLocale = (selectedLocales && selectedLocales[0]) || 'en';
let all404NotFoundPageContent = null;
// Initializes the server and mounts it in the generated build directory.
http
.createServer((req, res) => {
// If we are accessing the root, it should be redirected to the default language,
// We shouldn't get a 404 page.
if (req.url === '/') {
req.url = `/${mainLocale}`;
}
mount(req, res, async () => {
// Here we should handle the 404 page when the route is not found.
// 1. Check whether the language is supported or not.
// 2. If not, redirect to the default language.
// 3. If yes, Save the content and return directly for the next time.
if (all404NotFoundPageContent === null) {
const allSupportedLangs = await fs.readdir(
path.join(__dirname, 'locale')
);
all404NotFoundPageContent = new Map();
for (const lng of allSupportedLangs) {
all404NotFoundPageContent.set(lng, '');
}
}
let currentLng = req.url.split('/')[1];
if (!all404NotFoundPageContent.has(currentLng)) {
currentLng = mainLocale;
}
if (all404NotFoundPageContent.get(currentLng) === '') {
const notFoundPagePath = path.join(
__dirname,
'build',
`${currentLng}/404.html`
);
all404NotFoundPageContent.set(
currentLng,
await fs.readFile(notFoundPagePath, 'utf8')
);
}
res.end(all404NotFoundPageContent.get(currentLng));
});
})
.listen(port, () => {
console.log(
`\x1B[32mServer running at http://localhost:${port}/${mainLocale}/\x1B[39m`
);
});
if (!serveOnly) {
// Start the initial build of static HTML pages
build.copyStatic();
build.buildCSS();
build.fullBuild({ selectedLocales, preserveLocale });
}