-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
69 lines (50 loc) · 1.93 KB
/
Copy pathindex.js
File metadata and controls
69 lines (50 loc) · 1.93 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
//Dependencies
const http = require("http");
const url = require("url");
const config = require("./config");
// Create the server and pass to mainFunction
const server = http.createServer( (req,res)=> {
mainFunction( req, res);
})
// A main function for processing
const mainFunction = function( req, res) {
// Check url sent by user
const parsedUrl = url.parse( req.url, true);
// get the route
const path = parsedUrl.pathname;
const trimmedPath = path.replace(/^\/+|\/+$/g,'');
// Reply the request
//Pick the handler (default is not found)
var chosenHandler = router.has( trimmedPath) ? router.get( trimmedPath) : handler.notFound;
//Call the handler
chosenHandler( ( statusCode, payload)=> {
// set payload to chosen handler or empty one
var payload = typeof( payload) == 'object' ? payload : {};
var payloadString = JSON.stringify( payload);
//set the content type to JSON
res.setHeader("Content-Type","applications/json");
//set the status code
res.writeHead( statusCode);
res.end( payloadString);
// log the requested route and the response
console.log("Request received on path: ",trimmedPath);
console.log("Response : ", statusCode, payloadString);
});
};
// Listen on port set by config
server.listen( config.port, "localhost", ()=>{
console.log(`Server listening on port ${config.port} environment ${config.envName.toUpperCase()}`);
});
// A handler object
const handler = {};
// 404 for any route not managed
handler.notFound = ( callback)=> {
callback( 404);
}
// Reply with welcome message on route /hello
handler.hello = ( callback)=> {
callback( 200, {"message":"Welcome to Homework Assignment #1, Nodejs Master Class!!"})
}
// I'm using a map for the actual router
const router = new Map();
router.set("hello", handler.hello);