forked from mozilla/learning.mozilla.org
-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
84 lines (73 loc) · 2.11 KB
/
app.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
var path = require('path');
var fs = require('fs');
var express = require('express');
var Router = require('react-router');
var indexStaticWatcher = require('./lib/index-static-watcher').create();
var PORT = process.env.PORT || 8008;
var PRODUCTION = (process.env.NODE_ENV === 'production');
var DIST_DIR = path.join(__dirname, 'dist');
var indexStatic;
var router;
var app = express();
var startProdApp = function() {
console.log([
'Production mode enabled. Note that "npm install" is assumed to',
'have recently been run with NODE_ENV="production". If this is not',
'the case, some or all static assets may be out of date.'
].join('\n'));
indexStaticWatcher.build(function(err, newIndexStatic) {
if (err) {
throw err;
}
console.log('Built server-side bundle.');
updateIndexStatic(newIndexStatic);
app.listen(PORT, function() {
console.log('Listening on port', PORT);
});
});
};
var updateIndexStatic = function(newIndexStatic) {
indexStatic = newIndexStatic;
router = indexStatic ? Router.create({
routes: indexStatic.routes
}) : null;
};
if (!fs.existsSync(DIST_DIR)) {
fs.mkdirSync(DIST_DIR);
}
app.use(function(req, res, next) {
if (!router) {
return res.send('Please wait while the server-side bundle regenerates.');
}
if (req.path in indexStatic.REDIRECTS) {
return res.redirect(indexStatic.REDIRECTS[req.path]);
}
if (!router.match(req.url)) {
if (router.match(req.path + '/')) {
return res.redirect(req.path + '/');
}
return next('route');
}
indexStatic.generate(req.url, {}, function(err, html) {
if (err) {
return next(err);
}
return res.type('html').send(html);
});
});
app.use(express.static(DIST_DIR));
app.DIST_DIR = DIST_DIR;
app.updateIndexStatic = updateIndexStatic;
module.exports = app;
if (!module.parent) {
console.log('Initializing server.');
if (PRODUCTION) {
startProdApp();
} else {
console.log([
'This server can only be run as a script when NODE_ENV="production".',
'To run it in development mode, please use "npm run app".'
].join('\n'));
process.exit(1);
}
}