-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver.js
152 lines (140 loc) · 5.21 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
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
/* SETUP */
var mysql = require('mysql'); //imports mysql node module
const fs = require('fs');
const http = require('http');
var server = http.createServer(function (req, res) {
requestString = req.url.replace(/%20/g, ' ').slice(1);
requestString = requestString.replace(/%22/g, `"`).replace(/%60/g, "`");
console.log("requestString: ", requestString);
console.log("Request was made: " + requestString);
if (requestString.toLowerCase().startsWith("update")) { //update an entity
connection.query(requestString, function (error) {
if (error) throw error;
res.writeHead(200, { "Content-Type": 'text/plain' });
res.end();
});
} else if (requestString.toLowerCase().startsWith("insert")) { //add a new entity
connection.query(requestString, function (error) {
if (error) throw error;
res.writeHead(200, { "Content-Type": 'text/plain' });
res.end();
});
} else if (requestString.toLowerCase().startsWith("select")) { //display data
connection.query(requestString, function (error, results) {
if (error) throw error;
console.log("Result: ", JSON.stringify(results));
res.writeHead(200, { "Content-Type": 'text/plain' });
res.end(JSON.stringify(results));
});
} else if (requestString.toLowerCase().startsWith("delete")) {
connection.query(requestString, function (error) {
if (error) throw error;
res.writeHead(200, { "Content-Type": 'text/plain' });
res.end();
});
} else if (req.url == "/site.html") {
console.log("Site request");
res.writeHead(200, { "Content-Type": 'text/html' });
var myReadStream = fs.createReadStream('site.html', 'utf8');
myReadStream.pipe(res);
} else {
console.log("Bad query");
res.writeHead(200, { "Content-Type": 'text/plain' });
res.end();
}
});
server.listen(3000, 'localhost');
console.log("Server listening on port 3000");
/* Forward Declaration */
var loginInfo = new Object(); //Creates an empty object for login info (note: objects in JavaScript are more like dictionaries)
var configFile; //file read in by fs
var config; //object representation of config
var connection; //the connection to the MySQL server
var bad_db_flag = false; //flagged to true if database does not exist
/* Functions */
function initialize(callback = null) { //initial config setup
createConfigIfNoConfig(function () {
configFile = fs.readFileSync("config.json");
config = JSON.parse(configFile);
loginInfo.host = config.host;
loginInfo.user = config.user;
loginInfo.password = config.password;
loginInfo.database = config.database;
if (callback != null) {
callback();
}
});
}
function createConfigIfNoConfig(callback = null) {
file = "config.json";
fs.access(file, fs.constants.F_OK, (err) => {
if (err) {
console.log("Config file not detected - generating default config file. If your MySQL is not set up in the default way, you will likely soon be getting an access denied error :)");
var defaultConfig = {
host: "localhost",
user: "root",
password: "",
database: "dnd"
}
var configString = JSON.stringify(defaultConfig);
fs.writeFile("config.json", configString, function () {
callback();
});
} else {
callback();
}
});
}
function connect() { //connects to server
//Moves loginInfo from config into loginInfo object
connection = mysql.createConnection(loginInfo);
connection.connect();
console.log("Connected")
testQuery();
}
function testQuery() { //validates database setup
connection.query('SELECT 1 + 1 AS solution', function (error, results, fields) {
if (error) {
if (error.message.substring(0, 15) == "ER_BAD_DB_ERROR") {
bad_db_flag = true;
setup();
} else {
throw error;
}
}
if (!bad_db_flag) {
if (results[0].solution === 2) {
console.log('Test query successful');
console.log("Connection state: " + connection.state);
fillDB();
}
}
});
}
function setup() { //to be run if the database does not exist
var dbName = loginInfo.database;
delete loginInfo.database;
connection = mysql.createConnection(loginInfo);
connection.query(`CREATE DATABASE ${dbName}`, function () {
connection.query(`USE DATABASE ${dbName}`, function () {
loginInfo.database = dbName;
bad_db_flag = false;
testQuery();
});
});
}
function fillDB() { //populates database with data
var input = fs.createReadStream('DB Setup/setup_new.sql');
var rl = require('readline').createInterface({
input: input,
terminal: false
});
rl.on('line', function (line) {
connection.query(line);
})
rl.on('close', function () {
console.log("Database successfully populated.")
})
}
/* Main */
initialize(connect);