-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
62 lines (50 loc) · 1.44 KB
/
app.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
var DOCUMENT_ROOT = './public';
var DIRECTORY_INDEX = '/index.html';
var port = process.env.PORT || 8080;
var zlib = require('zlib');
var http = require('http');
var path = require('path');
var fs = require('fs');
http.createServer(function(request, response) {
// Remove query strings from uri
if (request.url.indexOf('?')>-1) {
request.url = request.url.substr(0, request.url.indexOf('?'));
}
// Remove query strings from uri
if (request.url == '/') {
request.url = DIRECTORY_INDEX;
}
var filePath = DOCUMENT_ROOT + request.url;
var extname = path.extname(filePath);
var acceptEncoding = request.headers['accept-encoding'];
if (!acceptEncoding) {
acceptEncoding = '';
}
path.exists(filePath, function(exists) {
if (exists) {
fs.readFile(filePath, function(error, content) {
if (error) {
response.writeHead(500);
response.end();
}
else {
var raw = fs.createReadStream(filePath);
if (acceptEncoding.match(/\bdeflate\b/)) {
response.writeHead(200, { 'content-encoding': 'deflate' });
raw.pipe(zlib.createDeflate()).pipe(response);
} else if (acceptEncoding.match(/\bgzip\b/)) {
response.writeHead(200, { 'content-encoding': 'gzip' });
raw.pipe(zlib.createGzip()).pipe(response);
} else {
response.writeHead(200, {});
raw.pipe(response);
}
}
});
}
else {
response.writeHead(404);
response.end();
}
});
}).listen(port);