-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
81 lines (66 loc) · 1.86 KB
/
server.js
File metadata and controls
81 lines (66 loc) · 1.86 KB
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
/**
*
* @type {module:http}
*/
/**
* System dependancy
*/
const http = require('http');
const fs = require('fs');
const path = require('path');
/**
* Global variables
*/
const rootPath = './www/';
const port = 3000;
const host = 'localhost';
const extensions = {
".html" : '{"Content-Type":"text/html"}',
".css" : '{"Content-Type":"text/css"}',
".js" : '{"Content-Type":"application/javascript"}',
".json" : '{"Content-Type":"application/json"}',
".png" : '{"Content-Type":"image/png"}',
".gif" : '{"Content-Type":"image/gif"}',
".jpg" : '{"Content-Type":"image/jpeg"}',
};
/**
* server
*/
http.createServer(function(req, res){
/**
*
* @param url
* @param options
* @returns {ReadStream}
*/
function setFileStream(url, options){
if(options === ''){
return fs.createReadStream(path.join(__dirname, rootPath , url));
}
return fs.createReadStream(path.join(__dirname, rootPath , url), options);
}
/**
* 404 response
*/
function set404(){
res.writeHead(404, extensions['.html']);
res.end("No Page Found");
}
if(req.url === "/"){
fs.readFile(rootPath +"index.html", "UTF-8", function(err, html){
res.writeHead(200, extensions['.html'] );
res.end(html);
});
}else if(req.url.match("\.css$")){
setFileStream(req.url,"UTF-8").pipe(res.writeHead(200, extensions['.css']));
}else if(req.url.match("\.js$")){
setFileStream(req.url,"UTF-8").pipe(res.writeHead(200, extensions['.js']));
}else if(req.url.match("\.json$")){
setFileStream(req.url,"UTF-8").pipe(res.writeHead(200, extensions['.json']));
}else if(req.url.match("\.png$")){
setFileStream(req.url).pipe(res.writeHead(200, extensions['.png']));
}else{
set404()
}
}).listen(port,host);
console.log('http://'+host+':'+port);