-
Notifications
You must be signed in to change notification settings - Fork 0
/
web.js
64 lines (46 loc) · 1.83 KB
/
web.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
var util = require('util');
var fs = require('fs');
var static = require('node-static');
var mustache = require('mustache');
var environment = process.env.NODE_ENV;
var port = process.env.PORT || 8080;
var serverOptions = {};
var errorTemplate;
// Default to development environment
if (!environment) {
process.env.NODE_ENV = 'development';
serverOptions.cache = false;
serverOptions.headers = {
'Cache-Control': 'no-cache, must-revalidate'
}
}
// Read template for errors
fs.readFile('error.template', function (error, data) {
if (error) {
console.error('Can\'t read error template. Ensure you have a file "error.template" in the root directory.');
throw error;
}
errorTemplate = data.toString();
});
var fileServer = new static.Server('./demo', serverOptions);
// Create HTTP server
require('http').createServer(function (request, response) {
// Serve file
fileServer.serve(request, response, function (error) {
// An error occured whilst trying to serve file
if (error) {
console.error('[%d %s] - %s', error.status, error.message, request.url);
// Serve an error page if one exists (e.g. 404.html), otherwise just return the error status
fs.exists(util.format('%s/%d.html', fileServer.root, error.status), function (exists) {
if (exists) {
fileServer.serveFile(util.format('/%d.html', error.status), error.status, {}, request, response);
} else {
response.writeHead(error.status, error.headers);
response.write(mustache.render(errorTemplate, { status: util.format('%d %s', error.status, error.message) }));
response.end();
}
});
}
});
}).listen(port);
console.log('Listening on :%d', port);