Created
October 28, 2018 19:29
-
-
Save ibaca/834224a4ef379c0a033437554a729f95 to your computer and use it in GitHub Desktop.
NodeJS master class - Assignment 1
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const http = require('http'); | |
const url = require('url'); | |
const StringDecoder = require('string_decoder').StringDecoder; | |
http.createServer((req, res) => service(req, res)).listen(4000, () => { | |
console.log("The server is listening on port " + 4000) | |
}); | |
const service = (req, res) => { | |
const parseUrl = url.parse(req.url, true); | |
const path = parseUrl.pathname.replace(/^\/+|\/+$/g, ''); | |
const query = parseUrl.query; | |
const method = req.method.toLowerCase(); | |
const headers = req.headers; | |
const decoder = new StringDecoder('utf-8'); | |
let buffer = ''; | |
req.on('data', data => buffer += decoder.write(data)); | |
req.on('end', () => { | |
buffer += decoder.end(); | |
const handler = typeof router[path] !== 'undefined' ? router[path] : router['notFound']; | |
const data = {'path': path, 'query': query, 'method': method, 'headers': headers, 'payload': buffer}; | |
handler(data, (statusCode, payload) => { | |
statusCode = typeof statusCode === 'number' ? statusCode : 200; | |
payload = typeof payload === 'object' ? payload : {}; | |
res.setHeader('Content-Type', 'application/json'); | |
res.writeHead(statusCode); | |
res.end(JSON.stringify(payload)); | |
console.log('Returning this response: ', statusCode, payload); | |
}); | |
}); | |
}; | |
const router = { | |
'hello': (data, res) => res(200, {'message': 'welcome!'}), | |
'notFound': (data, res) => res(404), | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment