-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
89 lines (79 loc) · 2.21 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
88
89
var http = require('http');
var fs = require('fs');
var path = require('path');
var mime = require('mime');
var cache = {};
var chatServer = require('./lib/chat_server.js');
var mysql = require('mysql');
var db = mysql.createConnection({
host: '127.0.0.1',
user: 'root',
password: 'password',
database: 'timetrack'
});
var server = http.createServer(function(request, response) {
var filePath = false;
switch(request.method) {
case 'POST':
break;
case 'GET':
switch(request.url) {
case '/':
filePath = 'public/index.html';
break;
default:
filePath = 'public' + request.url;
break;
}
break;
}
var absPath = './' + filePath;
serveStatic(response, cache, absPath);
});
chatServer.listen(server, db);
function send404(response) {
response.writeHead(404, {'Content-Type': 'text/plain'});
response.write('Error 404: resource not found.');
response.end();
}
function sendFile(response, filePath, fileContents) {
response.writeHead(
200,
{"content-type": mime.lookup(path.basename(filePath))}
);
response.end(fileContents);
}
function serveStatic(response, cache, absPath) {
if (cache[absPath]) {
sendFile(response, absPath, cache[absPath]);
} else {
fs.exists(absPath, function(exists) {
if (exists) {
fs.readFile(absPath, function(err, data) {
if (err) {
send404(response);
} else {
cache[absPath] = data;
sendFile(response, absPath, data);
}
});
} else {
send404(response);
}
});
}
}
db.query(
"CREATE TABLE IF NOT EXISTS chat ("
+ "id INT(10) NOT NULL AUTO_INCREMENT, "
+ "date DATETIME, "
+ "name LONGTEXT,"
+ "message LONGTEXT,"
+ "PRIMARY KEY(id))",
function(err) {
if (err) throw err;
console.log('Server started...');
server.listen(80, '127.0.0.1');
}
);
console.log('Server running at localhost:80/');