-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
68 lines (61 loc) · 1.75 KB
/
Copy pathserver.js
File metadata and controls
68 lines (61 loc) · 1.75 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
//modules
const http = require('http');
const fs = require('fs');
const path = require('path');
const mime = require('../../Users/CSeal/AppData/Local/Microsoft/TypeScript/2.9/node_modules/@types/mime');
const cache = {};
//config const
const publicDir = 'build';
const serverConf = {
port: 3001,
host: '127.0.0.1',
hostAlias: 'localhost'
}
//helpers function
const send404 = res => {
res.writeHead( 404, {"Content-Type": "text/plain"} );
res.end("404, Page nod found!");
}
//absPath(example) = ./public/index.html;
const sendFile = (res, filePath, fileContents) => {
res.writeHead( 200, {"Content-Type" : mime.getType( path.basename( filePath )),
"Cache-control" : "no-cache"} );
res.end( fileContents );
}
const getFile = (res, cache, absPath) => {
if ( cache[absPath] ){
sendFile( res, absPath, cache[absPath] );
} else {
fs.exists( absPath, exists => {
if( !exists ){
send404( res );
}
fs.readFile( absPath, ( err, data ) => {
if( err ){
send404( res );
}
cache[absPath] = data;
sendFile( res, absPath, data );
})
})
}
}
const staticServer = ( req, res ) => {
let filePath = '';
if (req.url === '/'){
filePath = path.join(__dirname, publicDir, 'index.html');
} else {
const requestFile = path.extname(req.url) !== '' ?
path.basename(req.url) : 'index.html'
filePath = path.join(__dirname, publicDir, req.url, requestFile);
}
console.log(filePath);
getFile(res, cache, filePath);
}
//static server eventListener
const server = http.createServer();
server.listen( serverConf.port, serverConf.hostAlias || serverConf.host);
server.on('request', ( req, res ) => {
staticServer( req, res );
});
console.log(`Server runing on ${serverConf.hostAlias || serverConf.host} an listning ${serverConf.port}`);