-
Notifications
You must be signed in to change notification settings - Fork 80
/
server.js
89 lines (70 loc) · 1.95 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
#!/usr/bin/env node
/*
server.js: launches a static file web server from the current folder
make executable with `chmod +x ./server.js`
run with `./server.js [port]`
where `[port]` is an optional HTTP port (8888 by default)
*/
(function() {
'use strict';
const
http = require('http'),
url = require('url'),
path = require('path'),
fs = require('fs'),
port = parseInt(process.argv[2] || 8888, 10),
mime = {
'.html' : ['text/html', 86400],
'.htm' : ['text/html', 86400],
'.css' : ['text/css', 86400],
'.js' : ['application/javascript', 86400],
'.json' : ['application/json', 86400],
'.jpg' : ['image/jpeg', 0],
'.jpeg' : ['image/jpeg', 0],
'.png' : ['image/png', 0],
'.gif' : ['image/gif', 0],
'.ico' : ['image/x-icon', 0],
'.svg' : ['image/svg+xml', 0],
'.txt' : ['text/plain', 86400],
'err' : ['text/plain', 30]
};
// new server
http.createServer(function(req, res) {
let
uri = url.parse(req.url).pathname,
filename = path.join(process.cwd(), uri);
// file available?
fs.access(filename, fs.constants.R_OK, (err) => {
// not found
if (err) {
serve(404, '404 Not Found\n');
return;
}
// index.html default
if (fs.statSync(filename).isDirectory()) filename += '/index.html';
// read file
fs.readFile(filename, (err, file) => {
if (err) {
// error reading
serve(500, err + '\n');
}
else {
// return file
serve(200, file, path.extname(filename));
}
});
});
// serve content
function serve(code, content, type) {
let head = mime[type] || mime['err'];
res.writeHead(code, {
'Content-Type' : head[0],
'Cache-Control' : 'must-revalidate, max-age=' + (head[1] || 2419200),
'Content-Length' : Buffer.byteLength(content)
});
res.write(content);
res.end();
}
}).listen(port);
console.log('Server running at http://localhost:' + port);
}());