Created
February 21, 2019 14:25
-
-
Save wayanjimmy/800535f67dc861cdfe62678f413b0c86 to your computer and use it in GitHub Desktop.
Assignment #1 - Node Master Class
This file contains hidden or 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
import http from 'http' | |
import url from 'url' | |
// config object | |
const config = { | |
httpPort: 8080 | |
} | |
// retrieve the third argument if user use custom port | |
if (process.argv.length > 2) { | |
let [param, value] = process.argv[2].split('=') | |
if (param === '-p') { | |
config.httpPort = +value | |
} | |
} | |
// general http responder | |
const respond = (res, data = {}, statusCode = 200) => { | |
res.setHeader('Content-Type', 'application/json') | |
res.writeHead(statusCode) | |
res.end(JSON.stringify(data)) | |
} | |
// create server | |
function createServer() { | |
return http.createServer((req, res) => { | |
let parsedUrl = url.parse(req.url, true) | |
// remove extra slash | |
let trimmedPath = parsedUrl.pathname.replace(/^\/+|\/+$/g, '') | |
if (trimmedPath === 'hello') { | |
respond(res, { message: 'hello world' }) | |
} else { | |
respond(res, { message: 'not found' }, 404) | |
} | |
}) | |
} | |
const server = createServer() | |
// start the server | |
server.listen(config.httpPort, () => { | |
console.log(`server is listening on port ${config.httpPort}`) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment