-
Notifications
You must be signed in to change notification settings - Fork 0
/
test-server.mjs
80 lines (68 loc) · 2.01 KB
/
test-server.mjs
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
// LICENSE: GNU GPL v3 You should have received a copy of the GNU General
// Public License along with this program. If not, see
// https://www.gnu.org/licenses/.
// File: test-server.mjs
// A simple example expressjs app that shows how to use the router,
// or allows it to be used on its own
import express from 'express';
import http from 'node:http';
import path from 'node:path';
import ogtfRouter from './ogtfRouter.mjs';
const app = express();
// mount router
app.use(await ogtfRouter({
ogepath: path.join(
process.__ogtfdirname,
'open-guide-editor'
),
baseurl: 'typesetting'
}));
// catch 404
app.use(function (req, res, next) {
res.status(404).type('txt').send('Error 404 Not Found');
});
// catch other errors
app.use(function (err, req, res, next) {
console.error(err.stack);
res.status(500).type('txt')
.send('Error 500 Server Error: ' + err.toString());
});
// disable X-Powered-By header to avoid attacks targeting Express
app.disable('x-powered-by');
// create and start server
let httpserver = http.createServer(app);
let portnum = parseInt(process.env.OGTFTESTSERVERPORT);
if (isNaN(portnum)) portnum = 14747;
httpserver.listen(portnum);
// report errors
httpserver.on('error', onError);
// report listening to stderr
httpserver.on('listening', () => {
const addr = httpserver.address();
console.log('HTTP server listening on port ' + addr.port.toString());
});
// shutdown gracefully if terminated
httpserver.on('SIGTERM', () => {
console.log('SIGTERM signal received: closing server');
httpserver.close(() => {
console.log('http server closed')
});
});
// handle specific listen errors with friendly messages
function onError(error) {
if (error.syscall !== 'listen') {
throw error;
}
switch (error.code) {
case 'EACCES':
console.error('ERROR: Port requires elevated privileges.');
process.exit(1);
break;
case 'EADDRINUSE':
console.error('ERROR: Port is already in use.');
process.exit(1);
break;
default:
throw error;
}
}