forked from filamentgroup/loadCSS
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
61 lines (48 loc) · 1.42 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
/* jshint esversion: 6 */
const fs = require('fs');
const http = require('http');
const path = require('path');
const port = 3000;
const server = http.createServer(requestHandler);
server.listen(port, (err) => {
if (err) {
return console.error('could not run server', err);
}
console.log(`server is listening on ${port}`);
});
const contentTypes = {
'.css': 'text/css',
'.html': 'text/html',
'.js': 'application/javascript',
};
function requestHandler (request, response) {
console.log(JSON.stringify(request.url));
try {
response.setHeader('charset', 'UTF-8');
response.setHeader('Cache-Control', 'max-age=500');
if (!path.extname(request.url)) {
request.url += '/index.html';
}
response.setHeader('Content-type', contentTypes[path.extname(request.url)]);
const content = fs.readFileSync(
path.join('.', request.url)
).toString().replace(/<!--#include virtual="([^"]+)" -->/g, (match, filepath) => fs.readFileSync(
path.resolve(path.dirname(path.join('.', request.url)), filepath)
));
if (request.url.endsWith('slow.css')) {
setTimeout(() => {
response.end( content );
}, 5000);
} else {
response.end( content );
}
} catch (error) {
const errorMessage = (error.message && (error.message + '\n' + error.stack)) || error;
if (errorMessage.includes('ENOENT')) {
response.statusCode = 404;
} else {
response.statusCode = 500;
}
response.end('<pre>' + errorMessage);
}
}