-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathindex.js
297 lines (257 loc) · 11.7 KB
/
index.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
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
'use strict';
/*
* Created by marketionist on 21.01.2017
*/
// #############################################################################
const http = require('http');
const fs = require('fs');
const path = require('path');
const packageName = '[node-testing-server]:';
/**
* Transforms incoming stream to string
* @param {stream} stream
* @param {function} callback
*/
function streamToString (stream, callback) {
let chunks = [];
stream.on('data', (chunk) => {
chunks.push(chunk);
});
stream.on('end', () => {
callback(Buffer.concat(chunks).toString());
});
}
let nodeTestingServer = {
// Config default options
config: {
hostname: 'localhost',
port: 3001,
logsEnabled: 0,
pages: {}
},
server: http.createServer((req, res) => {
const status200 = 200;
const status404 = 404;
// Show logs if they are enabled in nodeTestingServer.config.logsEnabled
if (nodeTestingServer.config.logsEnabled >= 1) {
console.log('\n========');
// Print incoming request METHOD, URL
console.log(`Request: ${req.method} ${req.url}`);
}
if (nodeTestingServer.config.logsEnabled === 2) {
// Print incoming request headers
console.log('\nRequest headers:\n', req.headers, '\n');
// Start counting response time
console.time('Response time');
}
if (req.method === 'POST') {
if (req.url === '/post') {
let chunks = [];
res.writeHead(status200, { 'Content-Type': 'application/json', 'Connection': 'close' });
req.on('data', (chunk) => {
chunks.push(chunk);
});
req.on('end', () => {
const data = Buffer.concat(chunks);
res.end(
`\nIncoming request headers: ${JSON.stringify(req.headers)}` +
`\nIncoming request body: ${JSON.stringify(JSON.parse(data))}`
);
// Show logs if they are enabled in nodeTestingServer.config.logsEnabled
if (nodeTestingServer.config.logsEnabled >= 1) {
const spacesToIndent = 4;
console.log(packageName, 'Served back /post body JSON from the server to the client');
// Print outcoming response CODE
console.log(`\nResponse status code: ${res.statusCode}`);
console.log(
'\nResponse data (incoming request body):',
JSON.stringify(JSON.parse(data), null, spacesToIndent)
);
console.log('========');
}
if (nodeTestingServer.config.logsEnabled === 2) {
// Print response time
console.log(' ^');
console.log(' |');
console.timeEnd('Response time');
}
return;
});
}
} else if (req.method === 'GET') {
if (req.url === '/') {
const isCalledExternally = __dirname.includes('node_modules');
let mainPagePath = path.join(__dirname, 'public/index.html');
const pathFromRoot = isCalledExternally ?
path.resolve(__dirname, '../..', 'public/index.html') :
mainPagePath;
fs.exists(pathFromRoot, (exists) => {
if (exists) {
mainPagePath = pathFromRoot;
} else {
console.log(
packageName,
'There is no "public/index.html" in your ' +
'root folder - so serving from ' +
'node_modules/node-testing-server/public/index.html'
);
}
res.writeHead(status200, { 'Content-Type': 'text/html', 'Connection': 'close' });
let stream = fs.createReadStream(mainPagePath);
streamToString(stream, (data) => {
res.end(data);
// Show logs if they are enabled in nodeTestingServer.config.logsEnabled
if (nodeTestingServer.config.logsEnabled >= 1) {
// Print outcoming response CODE
console.log(`\nResponse status code: ${res.statusCode}`);
console.log(packageName, `Served ${mainPagePath} from the server to the client`);
console.log('\nResponse data:', data);
console.log('========');
}
if (nodeTestingServer.config.logsEnabled === 2) {
console.log(' ^');
console.log(' |');
console.timeEnd('Response time');
}
});
});
return;
}
let fileURL = req.url;
let filePath = path.resolve(`public/${fileURL}`);
let fileExtension = path.extname(filePath);
// All supported file extensions
const supportedFileExtensions = [
'.html',
'.json',
'.js',
'.css',
'.jpg',
'.png'
];
// Set initial Content-Type
let contentType;
// Check fileExtension and set corresponding Content-Type
switch (fileExtension) {
case '.json':
contentType = 'application/json';
break;
case '.js':
contentType = 'text/javascript';
break;
case '.css':
contentType = 'text/css';
break;
case '.jpg':
contentType = 'image/jpg';
break;
case '.png':
contentType = 'image/png';
break;
default:
contentType = 'text/html';
}
if (supportedFileExtensions.indexOf(fileExtension) === -1) {
res.writeHead(status404, { 'Content-Type': 'text/html', 'Connection': 'close' });
res.end(`<h1>Error 404: ${fileExtension} is not among supported file formats:
${supportedFileExtensions.join(', ')}</h1>`);
// Show logs if they are enabled in nodeTestingServer.config.logsEnabled
if (nodeTestingServer.config.logsEnabled >= 1) {
// Print outcoming response CODE
console.log(`Response status code: ${res.statusCode}`);
console.log('========');
}
} else {
fs.exists(filePath, (exists) => {
if (!exists) {
if (typeof nodeTestingServer.config.pages[fileURL] === 'undefined') {
res.writeHead(status404, { 'Content-Type': 'text/html', 'Connection': 'close' });
res.end(`<h1>Error 404: ${fileURL} is not set in nodeTestingServer.config.pages</h1>`);
} else {
// If requested page cannot be found in public/ folder,
// then it will be generated from nodeTestingServer.config.pages
const pageStatusCode = nodeTestingServer.config.pages[fileURL].pageStatusCode || status200;
const pageBody = nodeTestingServer.config.pages[fileURL].pageBody ||
nodeTestingServer.config.pages[fileURL];
res.writeHead(pageStatusCode, { 'Content-Type': contentType, 'Connection': 'close' });
res.end(pageBody);
// Show logs if they are enabled in nodeTestingServer.config.logsEnabled
if (nodeTestingServer.config.logsEnabled >= 1) {
// Print outcoming response CODE
console.log(`\nResponse status code: ${res.statusCode}`);
console.log(`\n${packageName} Generated ${fileURL}` +
'from nodeTestingServer.config.pages');
console.log(`\nResponse data: ${pageBody}`);
console.log('========');
}
if (nodeTestingServer.config.logsEnabled === 2) {
console.log(' ^');
console.log(' |');
console.timeEnd('Response time');
}
}
return;
}
res.writeHead(
status200,
{ 'Content-Type': contentType, 'Connection': 'close' }
);
let stream = fs.createReadStream(filePath);
streamToString(stream, (data) => {
res.end(data);
// Show logs if they are enabled in nodeTestingServer.config.logsEnabled
if (nodeTestingServer.config.logsEnabled >= 1) {
// Print outcoming response CODE
console.log(`\nResponse status code: ${res.statusCode}`);
console.log(packageName, `Served ${filePath} from the server to the client`);
console.log('\nResponse data:', data);
console.log('========');
}
if (nodeTestingServer.config.logsEnabled === 2) {
console.log(' ^');
console.log(' |');
console.timeEnd('Response time');
}
});
return;
});
}
} else {
res.writeHead(
status404,
{ 'Content-Type': 'text/html', 'Connection': 'close' }
);
res.end(`<h1>Error 404: ${req.method} is not supported</h1>`);
// Show logs if they are enabled in nodeTestingServer.config.logsEnabled
if (nodeTestingServer.config.logsEnabled >= 1) {
// Print outcoming response CODE
console.log(`Response status code: ${res.statusCode}`);
console.log('========');
}
}
}),
start () {
return this.server.listen(
nodeTestingServer.config.port,
nodeTestingServer.config.hostname
)
.on('listening', () => console.log(
packageName,
`Server running at http://${nodeTestingServer.config.hostname}:${nodeTestingServer.config.port}/`))
.on('close', () => {
console.log(
packageName,
`Server stopped at http://${nodeTestingServer.config.hostname}:${nodeTestingServer.config.port}/`
);
// Exit gracefully
// process.exit(0);
})
.on('error', (err) => console.log('Error starting server:', err));
},
stop () {
return this.server.close(() => {
console.log('Server closed');
});
}
};
module.exports.nodeTestingServer = nodeTestingServer;