forked from UsingBlockchain/yourdlt-explorer
-
Notifications
You must be signed in to change notification settings - Fork 4
/
server.js
93 lines (79 loc) · 1.81 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
const fs = require('fs');
const http = require('http');
const PORT = 80;
const CONFIG_ROUTE = '/config';
const DEFAULT_CONFIG_PATH = '/src/config/default.json';
const STATIC_FOLDER = '/www';
const INDEX_HTML = '/index.html';
let ENV;
const readConfig = (callback) => {
const ENV = process.env;
fs.readFile(__dirname + DEFAULT_CONFIG_PATH, (err, data) => {
if (err) throw Error('Failed to read default config. ' + err);
else {
const defaultConfig = JSON.parse(data);
const parsedENV = {};
Object.keys(ENV).forEach(key => {
try {
if (defaultConfig[key]) {
parsedENV[key] = JSON.parse(ENV[key]);
}
}
catch(e) {
parsedENV[key] = ENV[key];
}
});
const mergedConfig = {
...defaultConfig,
...parsedENV
};
callback(mergedConfig);
}
});
};
const getFile = (url, errCallback, callback) => {
fs.readFile(__dirname + STATIC_FOLDER + url, (err, data) => {
if (err) {
if(typeof errCallback === 'function')
errCallback(err);
}
else
if(typeof callback === 'function')
callback(data);
});
};
const send = (res, data) => {
res.writeHead(200);
res.end(data);
};
const sendJSON = (res, data) => {
res.setHeader('Content-Type', 'application/json');
send(res, JSON.stringify(data));
}
const sendError = (res, err, code) => {
res.writeHead(code);
res.end(JSON.stringify(err));
return;
};
readConfig(res => {
ENV = res;
http.createServer((req, res) => {
if(req.url === '/')
req.url = INDEX_HTML;
if(req.url === CONFIG_ROUTE) {
sendJSON(res, ENV);
}
else {
getFile(req.url,
() => {
getFile(INDEX_HTML,
err => sendError(res, err, 404),
data => send(res, data)
);
},
data => send(res, data)
);
}
}).listen(ENV.PORT || PORT);
console.log('dHealth Explorer is running. Listening on port: ' + PORT);
});