forked from Patchx/boilerplate_netlify_repo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
87 lines (74 loc) · 2.04 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
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
// This script is only for localhosting the project
// --
// ----------------
// - Dependencies -
// ----------------
const http = require('http');
const fs = require("fs");
var path = require('path');
const opn = require('opn');
// --------------------
// - Global Constants -
// --------------------
const hostname = '127.0.0.1';
const port = 3000;
const build_path = './build/';
// ---------------------
// - Private Functions -
// ---------------------
function getContentType(extension_name) {
switch (extension_name) {
case '.js':
return 'text/javascript';
case '.css':
return 'text/css';
case '.json':
return 'application/json';
case '.png':
return 'image/png';
case '.jpg':
return 'image/jpg';
case '.pdf':
return 'application/pdf';
case '.wav':
return 'audio/wav';
default:
return 'text/html';
}
}
// -----------------
// - Create Server -
// -----------------
const server = http.createServer((request, response) => {
if (request.url == '/') {
var filePath = build_path + 'home';
} else {
var filePath = build_path + request.url;
}
const contentType = getContentType(path.extname(filePath));
if (contentType === 'text/html') {
filePath += '.html';
}
fs.readFile(filePath, function(error, content) {
if (error === null) {
response.writeHead(200, { 'Content-Type': contentType });
response.end(content, 'utf-8');
return true;
}
if (error.code == 'ENOENT'){
fs.readFile(build_path + '404.html', function(error, content) {
response.writeHead(404, { 'Content-Type': 'text/html' });
response.end(content, 'utf-8');
});
} else {
response.writeHead(500);
response.end('Sorry, check with the site admin for error: '+error.code+' ..\n');
response.end();
}
});
});
server.listen(port, hostname, () => {
const my_url = `http://${hostname}:${port}/`;
console.log(`Server running at ${my_url}`);
opn(my_url);
});