-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
239 lines (218 loc) · 7.67 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
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
/**
* This is a small and tiny Web server. Mostly serves static pages and files.
*
* To debug:
* To install node-inspector, to do once:
* $ set HTTP_PROXY=http://www-proxy.us.oracle.com:80 # if needed for the install
* $ npm install -g node-inspector
*
* To run node-inspector:
* $ node-inspector
*
* From another console:
* $ node --debug server.js
*/
"use strict";
process.title = 'TinyNodeServer';
// HTTP port
let port = 8080;
let http = require('http');
let fs = require('fs');
let verbose = false;
let workDir = process.cwd();
console.log("----------------------------------------------------");
console.log("Usage: node " + __filename + " --verbose:true|false --port:XXXX --wdir:path/to/working/dir");
console.log("----------------------------------------------------");
for (let i=0; i<process.argv.length; i++) {
console.log("arg #%d: %s", i, process.argv[i]);
}
if (typeof String.prototype.startsWith !== 'function') {
String.prototype.startsWith = (str) => {
return this.indexOf(str) === 0;
};
}
if (typeof String.prototype.endsWith !== 'function') {
String.prototype.endsWith = (suffix) => {
return this.indexOf(suffix, this.length - suffix.length) !== -1;
};
}
const VERBOSE_PRM = "--verbose:";
const PORT_PRM = "--port:";
const WDIR_PRM = "--wdir:";
if (process.argv.length > 2) {
for (let argc=2; argc<process.argv.length; argc++) {
if (process.argv[argc].startsWith(VERBOSE_PRM)) {
let value = process.argv[argc].substring(VERBOSE_PRM.length);
if (value !== 'true' && value !== 'false') {
console.log("Invalid verbose value [%s]. Only 'true' and 'false' are supported.", value);
process.exit(1);
}
verbose = (value === 'true');
} else if (process.argv[argc].startsWith(PORT_PRM)) {
let value = process.argv[argc].substring(PORT_PRM.length);
try {
port = parseInt(value);
} catch (err) {
console.log("Invalid integer for port value %s.", value);
process.exit(1);
}
} else if (process.argv[argc].startsWith(WDIR_PRM)) {
let value = process.argv[argc].substring(WDIR_PRM.length);
try {
process.chdir(value);
workDir = process.cwd();
} catch (err) {
console.log("Invalid new working directory %s.", value);
process.exit(1);
}
} else {
console.log("Unsupported parameter %s, ignored.", process.argv[argc]);
}
}
}
console.log("----------------------------------------------------");
console.log("Your working directory:", workDir);
console.log("----------------------------------------------------");
/**
* Small Simple and Stupid little web server.
* Very basic. Lighter than Express.
*/
let handler = (req, res) => {
let respContent = "";
if (verbose) {
console.log("Speaking HTTP from " + workDir); // was __dirname
console.log("Server received an HTTP Request:\n" + req.method + "\n" + req.url + "\n-------------");
console.log("ReqHeaders:" + JSON.stringify(req.headers, null, '\t'));
console.log('Request:' + req.url);
let prms = require('url').parse(req.url, true);
console.log(prms);
console.log("Search: [" + prms.search + "]");
console.log("-------------------------------");
}
if (req.url.startsWith("/verbose=")) {
if (req.method === "GET") {
verbose = (req.url.substring("/verbose=".length) === 'on');
res.end(JSON.stringify({verbose: verbose?'on':'off'}));
}
} else if (req.url.startsWith("/")) { // Assuming static resource
if (req.method === "GET") {
let resource = req.url.substring("/".length);
if (resource.length === 0) {
console.log('Defaulting to index.html');
resource = 'index.html';
}
if (resource.indexOf("?") > -1) {
resource = resource.substring(0, resource.indexOf("?"));
}
let exist = fs.existsSync(workDir + '/' + resource);
if (exist === true && fs.lstatSync(workDir + '/' + resource).isDirectory()) {
// try adding index.html
console.log('Defaulting to index.html...');
let resourceBackup = resource;
resource += ((resource.endsWith("/") ? "" : "/") + "index.html");
exist = fs.existsSync(workDir + '/' + resource);
if (!exist) {
resource = resourceBackup;
} else {
console.log(" >> From " + resourceBackup + " to " + resource);
}
} else {
if (verbose) {
console.log(workDir + '/' + resource + " not found");
}
}
console.log((exist === true ? "Loading static " : ">> Warning: not found << ") + req.url + " (" + resource + ")");
fs.readFile(workDir + '/' + resource,
(err, data) => {
if (err) {
res.writeHead(400);
return res.end('Error loading ' + resource);
}
if (verbose) {
console.log("Read resource content:\n---------------\n" + data + "\n--------------");
}
let contentType = "text/plain"; // Default
if (resource.endsWith(".css") || resource.endsWith(".css.map")) {
contentType = "text/css";
} else if (resource.endsWith(".html")) {
contentType = "text/html";
} else if (resource.endsWith(".xml")) {
contentType = "text/xml";
} else if (resource.endsWith(".js") || resource.endsWith(".js.map") || resource.endsWith(".map")) {
contentType = "text/javascript";
} else if (resource.endsWith(".jpg")) {
contentType = "image/jpg";
} else if (resource.endsWith(".jpeg")) {
contentType = "image/jpeg";
} else if (resource.endsWith(".gif")) {
contentType = "image/gif";
} else if (resource.endsWith(".png")) {
contentType = "image/png";
} else if (resource.endsWith(".ico")) {
contentType = "image/x-icon";
} else if (resource.endsWith(".svg")) {
contentType = "image/svg+xml";
} else if (resource.endsWith(".woff")) {
contentType = "application/x-font-woff";
} else if (resource.endsWith(".ttf")) {
contentType = "application/octet-stream";
} else {
console.log("+-------------------------------------------")
console.log("| Un-managed content type for " + resource);
console.log("| You should add it in '%s'", __filename);
console.log("+-------------------------------------------")
}
res.writeHead(200, {'Content-Type': contentType});
// console.log('Data is ' + typeof(data));
if (resource.endsWith(".jpg") ||
resource.endsWith(".jpeg") ||
resource.endsWith(".gif") ||
resource.endsWith(".ico") ||
resource.endsWith(".svg") ||
resource.endsWith(".woff") ||
resource.endsWith(".ttf") ||
resource.endsWith(".png")) {
// res.writeHead(200, {'Content-Type': 'image/gif' });
res.end(data, 'binary');
} else {
res.end(data.toString().replace('$PORT$', port.toString())); // Replace $PORT$ with the actual port value.
}
});
}
} else {
console.log("Unmanaged request: [" + req.url + "]");
respContent = "Response from " + req.url;
res.writeHead(404, {'Content-Type': 'text/plain'});
res.end(); // respContent);
}
}; // HTTP Handler
/**
* Helper function for escaping input strings
*/
function htmlEntities(str) {
return String(str).replace(/&/g, '&').replace(/</g, '<')
.replace(/>/g, '>').replace(/"/g, '"');
}
/**
* HTTP server
*/
console.log((new Date()) + ": Starting server on port " + port);
console.log(` Try http://localhost:${port}/oliv-components/index.html`);
console.log(` Try http://localhost:${port}/oliv-components/gallery.html`);
let server = http.createServer(handler);
process.on('uncaughtException', (err) => {
if (err.errno === 'EADDRINUSE') {
console.log("Address in use.");
} else {
console.log(err);
}
process.exit(1);
});
try {
server.listen(port, () => {
console.log((new Date()) + ": Server is listening on port " + port);
});
} catch (err) {
console.log("There was an error:");
console.log(err);
}