-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
40 lines (36 loc) · 1.06 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
const path = require('path');
const fs = require('fs');
let getContentType = function(resource){
let contentType = 'text/html';
if(resource.indexOf('.css') > -1){
contentType = 'text/css';
}else{
if(resource.indexOf('.png') > -1){
contentType = 'image/png';
}else{
if(resource.indexOf('.jpg') > -1){
contentType = 'image/jpg';
}else{
if(resource.indexOf('.ico') > -1){
contentType = 'image/x-icon';
}
}
}
}
return contentType;
}
const serverPath = function(req,res){
const isHome = path.normalize(req.url) === path.normalize('/');
const resource = (isHome) ? path.resolve(__dirname,`index.html`) : path.resolve(__dirname,`.${req.url}`);
fs.readFile(resource, function(err,data){
if(!err && data){
let contentType = getContentType(resource)
res.writeHead(200, {"Content-Type" : contentType});
res.end(data);
}else{
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end(`this page: ${resource} doesn't exist`);
}
});
};
module.exports = serverPath;