-
Notifications
You must be signed in to change notification settings - Fork 2
/
server.js
87 lines (71 loc) · 2.24 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
const express = require('express');
const app = express();
const path = require('path');
const fs = require('fs');
const schedule = require('node-schedule');
app.set('port', (process.env.PORT || 3030));
// Setting gandi variables
// that vhosts need.
global.gandi = {};
global.gandi.i = 0;
global.gandi.app = app;
global.gandi.vhosts = {};
// For local development, you may specify which host
// should be used as follows: `node server.js vhost="LOCALPROJECT"`
var localProject;
process.argv.forEach(function (val, index, array) {
var options = val.split('=');
if (options.length && options[0].match(/^vhost$/i)) {
localProject = options[1];
}
});
// ExpressJS middleware that requires and call
// a project's index.js based on the HTTP request host.
app.use((req, res, next) => {
global.gandi.i++;
if (!('host' in req.headers))
{ showError(req, res); }
var host = localProject ? localProject : getRequestHost(req);
var vhost = path.join(__dirname, host);
fs.access(vhost, fs.constants.R_OK, (err) =>
{
if (err) { showError (req, res); }
else
{
global.gandi.request = req;
global.gandi.response = res;
global.gandi.vhosts[vhost] = true;
var appVhost = require(vhost);
appVhost(req, res, next);
}
});
});
// Setting up expressjs
// to listen on process port.
app.listen(app.get('port'), function() {
console.log('Node app is running on port', app.get('port'));
});
// Uncache vhosts every day at 2AM
// to avoid a full reload
var uncacheVhosts = schedule.scheduleJob('* 2 * * *', function () {
Object.keys(require.cache).forEach(function(modulePath) {
for (vhost in global.gandi.vhosts)
{
var vhostRegex = new RegExp(vhost);
if (modulePath.match(vhostRegex))
{ delete require.cache[modulePath]; }
}
});
});
/*
* UTILITIES
********************/
function getRequestHost (req)
{ return req.headers['host'].split(':')[0]; }
// Showing error
// if host is not specified or vhost is unknown
function showError (req, res)
{
res.status(404);
res.send('<!DOCYTPE html><html><body>Vhost (<strong>'+getRequestHost(req)+'</strong>) is not specified or unknown - you may contact <a href="http://www.twitter.com/frenchcooc">@frenchcooc</a>\n');
}