Skip to content

Instantly share code, notes, and snippets.

@craigderington
Created June 29, 2016 18:35
Show Gist options
  • Save craigderington/5cb16a61d46f57ad7bf5498f575c2b60 to your computer and use it in GitHub Desktop.
Save craigderington/5cb16a61d46f57ad7bf5498f575c2b60 to your computer and use it in GitHub Desktop.
JSON API Server for NodeJS
var http = require('http');
var url = require('url');
var portNumber = Number(process.argv[2]);
function parseTime(time) {
return {
hour: time.getHours(),
minute: time.getMinutes(),
second: time.getSeconds()
}
}
function unixTime(time) {
return {
unixtime: time.getTime()
}
}
var server = http.createServer(function (request, response) {
var parsedUrl = url.parse(request.url, true);
var time = new Date(parsedUrl.query.iso);
var result
if (/^\/api\/parsetime/.test(request.url))
result = parseTime(time);
else if (/^\/api\/unixtime/.test(request.url))
result = unixTime(time);
if (result) {
response.writeHead(200, {'content-type': 'application/json'});
response.end(JSON.stringify(result));
} else {
response.writeHead(404);
response.end();
}
});
server.listen(portNumber, function() {
console.log('The server is listening on port number: ' + portNumber);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment