-
Notifications
You must be signed in to change notification settings - Fork 22
/
app.js
255 lines (228 loc) · 8.8 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
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
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
/**
* Web Server Object for DataFormsJS Unit Tests and Demos with Node.js
*
* This script allows for a basic web server to define routes in a similar to
* Express and other popular frameworks but only use Node.js built-in features
* without any outside dependencies.
*
* Important - This script is very minimal by design and only allows for
* very basic request and response features needed for local development,
* it works well but has few features so is not intended for production apps.
*
* Since this file is small you can step through the code using a debugger
* which makes it is useful for learning purposes.
*
* Example Usage:
* examples/server.js https://github.com/dataformsjs/dataformsjs/blob/master/examples/server.js
* test/server.js https://github.com/dataformsjs/dataformsjs/blob/master/test/server.js
*
* @link https://www.dataformsjs.com
* @author Conrad Sollitt (https://conradsollitt.com)
* @license MIT
*/
/* Validates online with both [jshint] and [eslint] */
/* Select [ECMA Version] = 2018 for [eslint] */
/* jshint esversion:8, node:true */
/* eslint-env node, es6 */
'use strict';
const http = require('http');
const { URL } = require('url');
const fs = require('fs');
const path = require('path');
const app = {
// Arrays for middleware and routes
middleware: [ setupResponse ],
routes: [],
// Config Options
mimeTypes: {
htm: 'text/html; charset=UTF-8',
html: 'text/html; charset=UTF-8',
css: 'text/css',
txt: 'text/plain',
md: 'text/markdown',
js: 'application/javascript',
jsx: 'application/jsx',
json: 'application/json',
graphql: 'application/graphql',
png: 'image/png',
jpg: 'image/jpeg',
svg: 'image/svg+xml',
ico: 'image/x-icon',
},
// Add Middleware
use: function (callback) {
this.middleware.push(callback);
},
// Add a GET Route
get: function (path, callback) {
this.routes.push({ path: path, method: 'GET', callback: callback });
},
// Add a POST Route
post: function (path, callback) {
this.routes.push({ path: path, method: 'POST', callback: callback });
},
// Allow the route to handle ANY method
route: function (path, callback) {
this.routes.push({ path: path, method: null, callback: callback });
},
// Used to check if a route matches, returns an array of [bool:matches, array:args]
routeMatches: (pattern, path) => {
// Quick check for exact match
if (pattern === path && pattern.indexOf(':') === -1) {
return [ true, [] ];
}
// Check for ':variables' and add to an array
const patternParts = pattern.split('/');
const pathParts = path.split('/');
if (patternParts.length === pathParts.length) {
const args = [];
for (let n = 0, m = pathParts.length; n < m; n++) {
if (patternParts[n] !== pathParts[n]) {
if (patternParts[n].length > 0 && patternParts[n].indexOf(':') === 0) {
args.push(pathParts[n]);
} else {
return [ false, [] ];
}
}
}
return [ true, args ]; // Matches with Variables
}
// Doesn't match
return [ false, null ];
},
// Call this to start the server
run: function(port, siteRootDir) {
const server = http.createServer(async (req, res) => {
try {
// Call middleware functions
for (let n = 0, m = this.middleware.length; n < m; n++) {
const fn = this.middleware[n];
if (fn.constructor.name === 'AsyncFunction') {
await fn(req, res);
} else {
fn(req, res);
}
// If headers are sent assume that middleware handled the response
if (res.headersSent) {
return;
}
}
// Match the requested path to a defined route
const reqMethod = req.method;
const reqPath = decodeURIComponent(new URL(req.url, `http://${req.headers.host}`).pathname);
for (let n = 0, m = this.routes.length; n < m; n++) {
// First check method [GET|POST|HEAD]
const method = this.routes[n].method;
if (!(method === reqMethod || (method === 'GET' && reqMethod === 'HEAD') || method === null)) {
continue;
}
// Match on path
const pattern = this.routes[n].path;
const [matches, args] = this.routeMatches(pattern, reqPath);
if (matches) {
const fn = this.routes[n].callback;
if (fn.constructor.name === 'AsyncFunction') {
await fn.apply(null, [req, res].concat(args));
} else {
fn.apply(null, [req, res].concat(args));
}
return;
}
}
// Does the request path match a file under the site's root directory? If so and
// `siteRootDir` is defined then the file will be sent, otherwise send a 404.
// A security check against Path Traversal Attacks in first performed in case
// this script is used on production servers.
if (siteRootDir === undefined || (reqPath.includes('../') || reqPath.includes('..\\'))) {
res.pageNotFound();
return;
}
const filePath = path.join(siteRootDir, reqPath);
res.file(filePath);
} catch (err) {
res.error(err);
}
});
server.listen(port, null, () => {
console.log(`Server running at http://127.0.0.1:${port}/`);
});
},
// Helper function
escapeHtml: (text) => {
if (text === undefined || text === null || typeof text === 'number') {
return text;
}
return String(text)
.replace(/&/g, '&')
.replace(/"/g, '"')
.replace(/'/g, ''')
.replace(/</g, '<')
.replace(/>/g, '>');
},
};
function setupResponse(req, res) {
// Allow middleware to add callback functions that get called on `res.send`
res.onSend = [];
// Send an HTML Response
res.html = (html) => {
res.setHeader('Content-Type', 'text/html; charset=UTF-8');
res.send(html);
};
// Send a JSON Response
res.json = (data) => {
res.setHeader('Content-Type', 'application/json');
res.send(JSON.stringify(data));
};
// Send a Text Response
res.text = (text) => {
res.setHeader('Content-Type', 'text/plain');
res.send(text);
};
// Send a 404 Page as an HTML Response
res.pageNotFound = () => {
res.statusCode = 404;
res.html('<h1>Page not found</h1><p><a href="/">Home</a>');
};
// Log error to console and send error in a 500 page as an HTML Response
res.error = (err) => {
console.error(err);
res.statusCode = 500;
const html = `<h1>An error has occurred</h1><p><pre>${app.escapeHtml(err.stack ? err.stack.toString() : err.toString())}</pre></p>`;
res.html(html);
};
// Send a Response from a File. If the file doesn't exist or the file type is
// not defined in mimeTypes then a 404 HTML Response will be sent to the client.
res.file = (filePath) => {
const data = filePath.split('.');
const fileType = data[data.length-1];
if (app.mimeTypes[fileType] === undefined) {
res.pageNotFound(); // File type not supported
return;
}
fs.readFile(filePath, (err, content) => {
if (err && err.code === 'ENOENT') {
res.pageNotFound(); // File not found
} else if (err) {
res.error(err);
} else {
res.setHeader('Content-Type', app.mimeTypes[fileType]);
res.send(content);
}
});
};
// Used internally once headers and status code are defined
res.send = (content) => {
// Middleware callback functions
for (let n = 0, m = res.onSend.length; n < m; n++) {
res.onSend[n](content);
}
// Send content
if (req.method === 'HEAD' || res.statusCode === 204 || res.statusCode === 304) {
res.end();
} else {
res.end(content);
}
};
}
// Export the app object
module.exports = app;