-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathserver.js
More file actions
97 lines (88 loc) · 3.39 KB
/
server.js
File metadata and controls
97 lines (88 loc) · 3.39 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
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
import {createRequire} from "module";
const require = createRequire(import.meta.url);
// load up env variables from the .env file
require('dotenv').config()
const http = require('http');
const fs = require('fs');
const url = require('url');
const figlet = require('figlet');
import {fileTypes} from "./file.js";
import {apiHandler} from "./api.js";
const server = http.createServer((req, res) => {
// if protocol is undefined, default to http for now
const base = ((req.protocol) ? req.protocol : "http") + '://' + req.headers.host + '/'
const fullURL = new url.URL(req.url, base)
const page = fullURL.pathname
const params = fullURL.searchParams
if (page === "/api") {
handleRes(undefined, null, params, res, undefined, true, false);
} else {
returnFile(page, res)
}
})
/**
* Makes sure there is a file in the correct location (hardcoded to public for now), if so then serve
* the file.
* @param {string} tmpFile
* @param {module:http.ServerResponse} res
*/
function returnFile(tmpFile, res) {
// account for index.html being the root page
let file = (tmpFile === "/") ? "/index.html" : tmpFile
// if the file exists in the public folder, serve it
if (fileExists(`public${file}`)) {
fs.readFile(`public${file}`, (err, data) => handleRes(err, data, null, res, file, true, true))
} else {
figlet('404!!', (err, data) => handleRes(err, data, null, res, file, false, true));
}
}
/**
* @param {string} path to check if file exists
*/
function fileExists(path) {
try {
fs.accessSync(path, fs.constants.F_OK)
} catch {
return false
}
return true
}
// TODO: Might be better to break this into multiple functions, as it
// takes 7 parameters.
/**
* Handles Response code, sends back the data to the client. Look at the filetypes object in file.js for
* the possible types that this function serves.
* @param {NodeJS.ErrnoException} err Nodejs error, something went awful if this is not falsy
* @param {Buffer} data data that was read from file
* @param {URLSearchParams} params if we are serving an api request then this is used
* @param {module:http.ServerResponse} res the response object, used to send back data to the client
* @param {string} file filepath used to check for filetype
* @param {boolean} success if the file was found this will be true allowing for the server to serve the file
* in question
* @param {boolean} isFile checks if we are sending a file or if its a api request. Handle Response will then cover both cases
*/
function handleRes(err, data, params, res, file, success, isFile) {
if (err) {
console.log('Something went wrong...');
console.dir(err);
return;
} else if (success) {
// the content type to use. should never be undefined
let suffix = (isFile) ? file.split('.')[1] : "json"
let cType = fileTypes[suffix] //splits the string into an array of 2 elements, from wherever '.' is and returns the extension
// just in case it is, set make sure there is a value
if (!cType) {
cType = ""
}
res.writeHead(200, {'Content-Type': cType});
} else {
res.writeHead(404)
}
if (isFile) {
res.end(data);
} else {
// we are sending json back to the client
apiHandler(params).then((d) => res.end(JSON.stringify(d)))
}
}
server.listen(process.env.PORT || 8080);