Created
September 1, 2016 16:14
-
-
Save azs06/53d2602ceafdb57081b01bf2b1d37fe4 to your computer and use it in GitHub Desktop.
learnyounode json server
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
| const http = require('http'); | |
| const url = require('url'); | |
| const port = process.argv[2] || 4200; | |
| let body = ''; | |
| let server = http.createServer((req, res)=>{ | |
| res.writeHead(200, { 'Content-Type': 'application/json' }); | |
| req.on('data',(chunk)=>{ | |
| body += chunk; | |
| }).on('end',()=>{ | |
| let queryUrl = url.parse(req.url, true); | |
| let pathArray = queryUrl.pathname.split('/'); | |
| if(pathArray[1] === 'api'){ | |
| let query = queryUrl.query; | |
| let newDate = new Date(query.iso); | |
| if(pathArray[2] === 'parsetime'){ | |
| let dateObj = { | |
| hour: newDate.getHours(), | |
| minute: newDate.getMinutes(), | |
| second: newDate.getSeconds() | |
| } | |
| // console.log(JSON.stringify(dateObj)); | |
| res.end(JSON.stringify(dateObj)); | |
| }else if(pathArray[2] === 'unixtime'){ | |
| let unixtime = { | |
| unixtime: Date.parse(query.iso) | |
| } | |
| res.end(JSON.stringify(unixtime)); | |
| } | |
| }else{ | |
| // console.log('Invalid api path'); | |
| res.end('Invalid api path'); | |
| } | |
| }); | |
| }); | |
| server.listen(port, ()=>{ | |
| console.log('server running at port ' + port); | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment