-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
38 lines (35 loc) · 1.01 KB
/
server.js
File metadata and controls
38 lines (35 loc) · 1.01 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
const http = require('http');
const url = require('url');
const Listeners = [];
const HTTPClient = http.createServer((req, res) => {
const urlObj = url.parse(req.url, true);
let listeners = Listeners.filter(listener => listener.key.pathname === urlObj.pathname && listener.key.method === req.method);
let body = '';
req.on('data', chunk => {
body += chunk.toString();
});
req.on('end', () => {
listeners.forEach(listener => listener.callback(req, res, urlObj, body));
if(listeners.length === 0)
{
res.writeHead(404, {'Content-Type' : 'text/plain'});
res.end('Page not found');
}
})
});
const AddListener = (path, callback, method = 'GET') => {
Listeners.push({
key: {
pathname: path,
method: method,
},
callback: callback,
});
}
HTTPClient.listen(3000, () => {
console.log('Booted up client');
});
module.exports = {
HTTPClient: HTTPClient,
AddListener: AddListener,
};