Skip to content

Instantly share code, notes, and snippets.

@azs06
Created September 1, 2016 16:14
Show Gist options
  • Select an option

  • Save azs06/53d2602ceafdb57081b01bf2b1d37fe4 to your computer and use it in GitHub Desktop.

Select an option

Save azs06/53d2602ceafdb57081b01bf2b1d37fe4 to your computer and use it in GitHub Desktop.
learnyounode json server
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