lilobase
8/3/2017 - 2:44 PM

learnyounode_httpjsonapiserver.js

const http = require('http');
const url = require('url');

const server = http.createServer(({url: path}, res) => {
    const {pathname, query} = url.parse(path);
    const date = new Date(query.split('=')[1]);

    const response = content => {
        res.writeHead(200, {'Content-Type': 'application/json'});
        res.end(JSON.stringify(content));
    };
    const notFound = () => {
        res.writeHead(404);
        res.end();
    };

    if (pathname === '/api/parsetime')
        return response({
            hour: date.getHours(),
            minute: date.getMinutes(),
            second: date.getSeconds()
        });
    
    if (pathname === '/api/unixtime')
        return response({
            unixTime: date.getTime()
        });

    return notFound();
});

server.listen(process.argv[2]);